黑马程序员_学习笔记第12天——多线程2

来源:互联网 发布:找不到windows update 编辑:程序博客网 时间:2024/06/05 04:08
---------------------- ASP.Net+Android+IOS开发、href="http://edu.csdn.net"target="blank">.Net培训、期待与您交流! ----------------------

1、wait,notify(),notifyAll()都使用在同步中,因为要对持有监视器(锁)的线程操作,所以要使用在同步中,因为只有同步才具有锁。

2、为什么这些操作线程的方法要定义Object类中呢?

因为这些方法在操作同步线程时,都必须要标识他们所操作线程持有的锁,只有同一个锁上的被等待线程,可以被同一个锁上notify唤醒,不可以对不同锁中的线程进行唤醒。也就是说,等待和唤醒必须是同一个锁。而锁可以是任意对象,所以可以被任意对象调用的方法定义在Object类中。

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class InputOutDemo {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Res r = new Res();  
  5.           
  6.         /*Input in = new Input(r); 
  7.         Output out = new Output(r); 
  8.          
  9.         Thread t1 = new Thread(in); 
  10.         Thread t2 = new Thread(out); 
  11.          
  12.         t1.start(); 
  13.         t2.start(); 
  14. <span style="white-space:pre">      </span>*/  
  15.         new Thread(new Input(r)).start();  
  16.         new Thread(new Output(r)).start();  
  17.     }  
  18.   
  19. }  
  20. class Res {   
  21.     private String name;  
  22.     private String sex;  
  23.     private boolean flag = false;  
  24.       
  25.     public synchronized void set(String name,String sex) {  
  26.         if(flag)  
  27.             try {this.wait();}catch (Exception e) {}  
  28.         this.name = name;  
  29.         this.sex = sex;  
  30.         flag = true;  
  31.         this.notify();  
  32.     }  
  33.     public synchronized void out(){  
  34.         if(!flag)  
  35.             try {this.wait();}catch (Exception e) {}  
  36.         System.out.println(name+"........"+sex);  
  37.         flag = false;  
  38.         this.notify();  
  39.     }  
  40. }  
  41.   
  42. class Input implements Runnable {  
  43.     private Res r;  
  44.     Input(Res r) {  
  45.         this.r = r;  
  46.     }  
  47.     int x ;  
  48.       
  49.     public void run() {  
  50.         while(true) {  
  51.             /*synchronized(r){ 
  52.                 if(r.flag) 
  53.                     try {r.wait();}catch (Exception e) {}*/  
  54.                 if(x==0){  
  55.                     r.set("mike","man");  
  56.                 }  
  57.                 else{  
  58.                     r.set("丽丽","女女女女女");  
  59.                 }  
  60.                 x= (x+1)%2;  
  61. /*              r.flag = true; 
  62.                 r.notify();*/  
  63.         //  }     
  64.         }  
  65.     }  
  66. }  
  67.   
  68. class Output implements Runnable {  
  69.     private Res r;  
  70.     Output(Res r) {  
  71.         this.r = r ;  
  72.     }  
  73.     public void run() {  
  74.         while(true) {     
  75.             /*synchronized(r){ 
  76.                 if(!r.flag) 
  77.                     try {r.wait();}catch (Exception e) {} 
  78.                 System.out.println(r.name+"...."+r.sex); 
  79.                 r.flag = false; 
  80.                 r.notify(); 
  81.             } 
  82.             */  
  83.               
  84.             r.out();  
  85.         }  
  86.           
  87.     }  
  88. }  

3、对于多个生产者和消费者,为什么要定义while判断标记:因为让被唤醒的线程再一次判断标记。

      为什么要定义notifyAll:因为需要唤醒对方线程,因为只用notify,容易出现只唤醒本方线程的情况,导致程序中的所有线程都等待。

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class ProducerConsumerDemo {  
  2.   
  3.     public static void main(String[] args) {  
  4.         // TODO Auto-generated method stub  
  5.   
  6.         Resource r = new Resource();  
  7.         Producer pro = new Producer(r);  
  8.         Consumer con = new Consumer(r);  
  9.         Thread t1 = new Thread(pro);  
  10.         Thread t2 = new Thread(con);  
  11.         Thread t3 = new Thread(pro);  
  12.         Thread t4 = new Thread(con);  
  13.         t1.start();  
  14.         t2.start();  
  15.         t3.start();  
  16.         t4.start();  
  17.     }  
  18.   
  19. }  
  20. class Resource {  
  21.     private String name ;  
  22.     private int count = 1 ;  
  23.     private boolean flag = false;  
  24.       
  25.     public synchronized void set(String name ){  
  26.         while(flag)  
  27.             try {wait();}catch (Exception e) {}  
  28.         this.name = name+"--"+count++;  
  29.           
  30.         System.out.println(Thread.currentThread().getName()+"........生产者........."+this.name);  
  31.         flag = true;  
  32.         this.notifyAll();  
  33.     }  
  34.     public synchronized void out() {  
  35.         while(!flag)  
  36.             try {wait();}catch (Exception e) {}  
  37.         System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);  
  38.         flag = false;  
  39.         this.notifyAll();  
  40.     }  
  41.       
  42. }  
  43.   
  44. class Producer implements Runnable {  
  45.     private Resource res;  
  46.     Producer(Resource res) {  
  47.         this.res = res;  
  48.     }  
  49.     public void run() {  
  50.         while(true) {  
  51.             res.set("+商品+");  
  52.         }  
  53.     }  
  54. }  
  55.   
  56. class Consumer implements Runnable {  
  57.     private Resource res;  
  58.     Consumer(Resource res) {  
  59.         this.res=res;  
  60.     }  
  61.     public void run() {  
  62.         while (true) {  
  63.             res.out();  
  64.         }  
  65.     }  
  66. }  


4、jdk1.5中提供了多线程升级解决方法,将同步Synchronized替换成了显示的Lock操作,将Object 中的wait,notify,notifyAll,替换成了Condition对象,该对象可以Lock锁,进行获取。该示例中,实现了本方只唤醒对方的操作。

没有Lock之前,一个锁对应一个wait、notify,有了之后,可以对应多个wait、notify

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. import java.util.concurrent.locks.Condition;  
  2. import java.util.concurrent.locks.Lock;  
  3. import java.util.concurrent.locks.ReentrantLock;  
  4.   
  5. public class ProducerConsumerDemo2 {  
  6.   
  7.     public static void main(String[] args) {  
  8.         // TODO Auto-generated method stub  
  9.         Resource2 r = new Resource2();  
  10.         Producer2 pro = new Producer2(r);  
  11.         Consumer2 con = new Consumer2(r);  
  12.         Thread t1 = new Thread(pro);  
  13.         Thread t2 = new Thread(con);  
  14.         Thread t3 = new Thread(pro);  
  15.         Thread t4 = new Thread(con);  
  16.         t1.start();  
  17.         t2.start();  
  18.         t3.start();  
  19.         t4.start();  
  20.     }  
  21.   
  22. }  
  23. class Resource2 {  
  24.     private String name ;  
  25.     private int count = 1 ;  
  26.     private boolean flag = false;  
  27.       
  28.     private Lock lock = new ReentrantLock();  
  29.     private Condition condition_pro = lock.newCondition();  
  30.     private Condition condition_con = lock.newCondition();  
  31.       
  32.     public synchronized void set(String name )throws InterruptedException{  
  33.         lock.lock();  
  34.         try{  
  35.             while(flag)  
  36.                 condition_pro.await();  
  37.             this.name = name+"--"+count++;  
  38.               
  39.             System.out.println(Thread.currentThread().getName()+"........生产者........."+this.name);  
  40.             flag = true;  
  41.             condition_con.signal();  
  42.         }  
  43.         finally{  
  44.             lock.unlock();//释放锁的动作一定要执行  
  45.         }  
  46.           
  47.     }  
  48.     public void out() throws InterruptedException{  
  49.         lock.lock();  
  50.         try{  
  51.             while(!flag)  
  52.                 condition_con.await();  
  53.             System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);  
  54.             flag = false;  
  55.             condition_pro.signal();  
  56.         }  
  57.         finally {  
  58.             lock.unlock();  
  59.         }  
  60.     }  
  61.       
  62. }  
  63.   
  64. class Producer2 implements Runnable {  
  65.     private Resource2 res;  
  66.     Producer2(Resource2 res) {  
  67.         this.res = res;  
  68.     }  
  69.     public void run() {  
  70.         while(true) {  
  71.             try{  
  72.                 res.set("+商品+");  
  73.             } catch(InterruptedException e) {  
  74.                   
  75.             }  
  76.               
  77.         }  
  78.     }  
  79. }  
  80.   
  81. class Consumer2 implements Runnable {  
  82.     private Resource2 res;  
  83.     Consumer2(Resource2 res) {  
  84.         this.res=res;  
  85.     }  
  86.     public void run() {  
  87.         while (true) {  
  88.             try {  
  89.                 res.out();  
  90.             }catch(InterruptedException e) {  
  91.                   
  92.             }  
  93.               
  94.         }  
  95.     }  
  96. }  

5、stop方法已经过时,如何停止线程?

只有一种方法,run方法结束。

开启多线程运行,运行代码通常是循环结构,只要控制住循环,就可以让run方法结束,也就是线程结束。

特殊情况:当线程处于了冻结状态,就不会读取到标记,那么线程就不会结束。

当没有指定的方式让冻结的线程恢复到运行状态时,这时需要对冻结进行清除。强制让线程恢复到运行状态中来,这样就可以操作标记让线程结束。

Thread类提供该方法interrupt();

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class StopThreadDemo {  
  2.   
  3.     public static void main(String[] args) {  
  4.         // TODO Auto-generated method stub  
  5.   
  6.         StopThread st = new StopThread();  
  7.           
  8.         Thread t1 = new Thread(st);  
  9.         Thread t2 = new Thread(st);  
  10.           
  11.         t1.start();  
  12.         t2.start();  
  13.           
  14.         int num = 0 ;  
  15.         while(true) {  
  16.             if(num++==60) {  
  17.                 //st.changeFlag();  
  18.                 t1.interrupt();  
  19.                 t2.interrupt();  
  20.                 break;  
  21.             }  
  22.             System.out.println(Thread.currentThread().getName()+"----main-----");  
  23.         }  
  24.     }  
  25.   
  26. }  
  27.   
  28. class StopThread implements Runnable{  
  29.     private boolean flag = true;  
  30.     public synchronized void run() {  
  31.         while(flag) {  
  32.             try {  
  33.                 wait();  
  34.             } catch(InterruptedException e) {  
  35.                 System.out.println(Thread.currentThread().getName()+"-----Exception");  
  36.                 flag = false;  
  37.             }  
  38.             System.out.println(Thread.currentThread().getName()+"------run------");  
  39.         }  
  40.     }  
  41.     public void changeFlag() {  
  42.         flag = false;  
  43.     }  
  44.       
  45. }  

6、守护线程:setDaemon(true);该方法必须放在线程开启(start)之前,当正在运行的线程都是守护线程时,java虚拟机退出。

7、join特点:当A线程执行到了B线程的join()方法时,A就会等待,等B线程都执行完,A才会执行。join可以用来临时加入线程执行。

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class JoinDemo {  
  2.   
  3.     public static void main(String[] args) throws Exception{  
  4.         // TODO Auto-generated method stub  
  5.   
  6.         Demo d = new Demo();  
  7.           
  8.         Thread t1 = new Thread(d);  
  9.         Thread t2 = new Thread(d);  
  10.           
  11.         t1.start();  
  12.         t1.join();  
  13.         t2.start();  
  14.           
  15.         for(int x=0; x<80 ; x++) {  
  16.             System.out.println("main...."+x);  
  17.         }  
  18.         System.out.println("over");  
  19.     }  
  20.   
  21. }  
  22. class Demo implements Runnable {  
  23.     public void run() {  
  24.         for ( int x = 0; x<70; x++) {  
  25.             System.out.println(Thread.currentThread().getName()+"..."+x);  
  26.         }  
  27.     }  
  28. }  

8、优先级:

设置优先级: t1.setPriority(Thread.MAX_PRIORITY),或MIN_PRIORITY或NORM_PRIORITY,(优先级1-10),正常的都为5级

9、yield()暂停当前正在执行的线程对象,并执行其它线程。Thread.yield()

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class ThreadTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         // TODO Auto-generated method stub  
  5.         new Thread() {  
  6.             public void run() {  
  7.                 for(int x=0; x<100; x++) {  
  8.                     System.out.println(Thread.currentThread().getName()+"---1");  
  9.                 }  
  10.             }  
  11.         }.start();  
  12.           
  13.         for(int x=0; x<100; x++) {  
  14.             System.out.println(Thread.currentThread()+"----2");  
  15.         }  
  16.           
  17.         Runnable r = new Runnable() {  
  18.             public void run() {  
  19.                 for(int x=0; x<100; x++) {  
  20.                     System.out.println(Thread.currentThread()+"----3");  
  21.                 }  
  22.             }  
  23.         };  
  24.         new Thread(r).start();  
  25.   
  26.     }  
  27.   
  28. }  


---------------------- ASP.Net+Android+IOS开发、href="http://edu.csdn.net"target="blank">.Net培训、期待与您交流! ----------------------详细请查看:http://edu.csdn.net
0 0