黑马程序员——多线程(Lock、setDaemon、join、setPriority、yield)

来源:互联网 发布:精点数据 编辑:程序博客网 时间:2024/05/18 00:11

-----------android培训java培训、java学习型技术博客、期待与您交流!------------

JDK1.5版本新特性:

提供了多线成的升级解决方案。

将同步Sysnchronized替换成现实Lock操作。

将Object中的wait,notify,notifyAll,替换Condition对象。

该对象可以Lock锁 进行获取。


     private Lock lock = new ReentrantLock();//锁对象 相当于synchronized 

private Condition condition_pro = lock.newCondition();// 生产者的等待与唤醒
private Condition condition_con = lock.newCondition();// 消费者的等待与唤醒

举例程序:

在该例中实现了本方只唤醒对方的操作

import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class ProducerConsumerDemo {public static void main(String[] args) {Resource r = new Resource();Producer pro = new Producer(r);Consumer con = new Consumer(r);Thread t1 = new Thread(pro);Thread t2 = new Thread(pro);Thread t3= new Thread(con);Thread t4 = new Thread(con);t1.start();t2.start();t3.start();t4.start();}}class Resource{private String name;private int count = 1;private boolean flag = false;private Lock lock = new ReentrantLock();//锁对象 相当于synchronized private Condition condition_pro = lock.newCondition();// 生产者的等待与唤醒private Condition condition_con = lock.newCondition();// 消费者的等待与唤醒public  void set(String name) throws InterruptedException{lock.lock();//加锁try {while(flag)condition_pro.await();this.name = name + "__"+count++;System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);flag = true;condition_con.signal();//唤醒一个等待线程}finally{lock.unlock();//解锁}}public  void out() throws InterruptedException{lock.lock();try{while(!flag)condition_con.await();System.out.println(Thread.currentThread().getName()+"...消费者......"+this.name);flag = false;condition_pro.signal();}finally{lock.unlock();//释放锁的动作一定要执行。}}}class Producer implements Runnable{private Resource res;Producer(Resource res){this.res = res;}public void run(){while(true){try {res.set("+商品+");} catch (InterruptedException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}}}class Consumer implements Runnable{private Resource res;Consumer(Resource res){this.res = res;}public void run(){while(true){try {res.out();} catch (InterruptedException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}}}

 

停止线程:

stop方法已经过时。


如何停止线程?

只有一种,run方法结束。

开启多线程运行,运行代码通常是循环结构。


只要控制住循环,就可以让run方法结束,也就是线程结束。

<span style="font-family:SimSun;font-size:18px;color:#555555;">/* * 特殊情况: * 当线程处于冻结状态。 * 就不会读取到标记。那么线程就不会结束。 *  *  * 当没有指定的方法让冻结的线程恢复到运行状态时,这时需要进行清除。 * 强制让线程恢复到运行状态中来。这样就可以操作标记让线程结束。 *  * Thread类提供该方法interrupt(); */class StopThread implements Runnable{private boolean flag = true;public synchronized void run(){while(flag){try {wait();} catch (Exception e) {System.out.println(Thread.currentThread().getName()+"...Exception");flag = false;}System.out.println(Thread.currentThread().getName()+"...run");}}public void changeFlog(){flag = false;}}public class StopThreadDemo {public static void main(String[] args) {StopThread st = new StopThread();Thread t1 = new Thread(st);Thread t2 = new Thread(st);t1.start();t2.start();int num =0;while(true){if(num++ == 60){//st.changeFlog();t1.interrupt();t2.interrupt();break;}System.out.println(Thread.currentThread().getName()+"......."+num);}System.out.println("over");}}</span>

void setDaemon(boolean on) //将该线程标记为守护线程或用户线程。

该方法必须在线程启动之前调用。

当正在运行的线程都是守护线程时,Java虚拟机退出。

<span style="font-family:SimSun;font-size:18px;color:#555555;">public class StopThreadDemo {public static void main(String[] args) {StopThread st = new StopThread();Thread t1 = new Thread(st);Thread t2 = new Thread(st);t1.setDaemon(true);//关键位置t2.setDaemon(true);t1.start();t2.start();int num =0;while(true){if(num++ == 60){//st.changeFlog();//t1.interrupt();//t2.interrupt();break;}System.out.println(Thread.currentThread().getName()+"......."+num);}System.out.println("over");}}</span>
//主线程结束,子线程在等待状态也结束。
class StopThread implements Runnable{private boolean flag = true;public synchronized void run(){while(flag){try {wait();//有没有等待都结束} catch (Exception e) {System.out.println(Thread.currentThread().getName()+"...Exception");flag = false;}System.out.println(Thread.currentThread().getName()+"...run");}}public void changeFlog(){flag = false;}}
//子线程无线循环  只要主线程结束子线程也结束
class StopThread implements Runnable{private boolean flag = true;public  void run(){while(flag){System.out.println(Thread.currentThread().getName()+"...run");}}public void changeFlog(){flag = false;}}

Public final void join()

throws InterruptedException

等待该线程终止。

<span style="font-family:SimSun;font-size:18px;color:#555555;">class Demo implements Runnable{public void run(){for(int x = 0 ; x<70;x++){System.out.println(Thread.currentThread().getName()+"....."+x);}}}public class JoinDemo {public static void main(String[] args) throws Exception{Demo d = new Demo();Thread t1 = new Thread(d);Thread t2 = new Thread(d);t1.start();t1.join();//t1抢夺cup执行权t2.start();for(int x = 0; x<80;x++){System.out.println("main..."+x);}System.out.println("over");}}</span>

程序运行效果:

t1执行完后,main线程和t2线程才执行。

临时加入一个线程。

join:

当A线程执行到了B线程的join()方法时,A就会等待。等B线程执行完,A才会执行。

 join可以用来临时加入线程执行。


String toString()

返回该线程的字符串表现形式,包括线程名称,优先级和线程组。

优先级代表抢cpu的执行权频率。

所有线程的优先级为5.


setPriority(int newPriority)

更改线程的优先级。

最低优先级、默认优先级、最高优先级

1、5、10

MIN_PRIORITY NORM_PRIORITY MAX_PRIORITY 


public static void yield()

暂停当前正在执行的线程对象,并执行其他线程。

减缓当前线程执行的频率。

<span style="font-family:SimSun;font-size:18px;color:#555555;">/* * 开发时线程的一般写法 */public class ThreadTest {public static void main(String[] args) {new Thread(){public void run(){for(int x= 0 ; x<100;x++)System.out.println(Thread.currentThread().getName()+"....."+x);}}.start();Runnable r = new Runnable(){public void run(){for(int x= 0 ; x<100;x++)System.out.println(Thread.currentThread().getName()+"....."+x);}};new Thread(r).start();}}</span>

0 0
原创粉丝点击