你的位置:首页 > 软件开发 > Java > 黑马程序员系列第二篇 多线程(2)

黑马程序员系列第二篇 多线程(2)

发布时间:2015-11-10 23:00:27
ASP.Net+Android+IOS开发 、Net培训、期待与您交流! (前言:本篇文章主要依据毕向东老师的课程视频整理而成,如要详细学习,请观看毕老师视频 百度网盘链接地址:http://pan.baidu.com/s/1sjQRHDz) 目录:1、线程通 ...

 ASP.Net+Android+IOS开发  、Net培训、期待与您交流!

 

(前言:本篇文章主要依据毕向东老师的课程视频整理而成,如要详细学习,请观看毕老师视频  百度网盘链接地址:http://pan.baidu.com/s/1sjQRHDz)

 

目录:1、线程通信--生产消费者示例(线程通信安全、等待唤醒机制)    2、停止线程、及其会出现的问题、及解决的办法    3、守护线程及几个Thread的方法                   4、工作中线程的常见写法

        1、线程通信--生产消费者示例

代码示例:

 1 public class ProducerConsumer { 2 //需求:生产和消费行为依次进行。   设置产品为BMW  设置生产者和消费者线程各两个 3   public static void main(String[] args) { 4      5     Product pro=new Product(); 6      7     new Thread(new Producter(pro)).start();     8     new Thread(new Consumer(pro)).start(); 9     new Thread(new Producter(pro)).start();10     new Thread(new Consumer(pro)).start();11 12   }13 }14 class Product{15   16   private String name;17   private int No=1;18   boolean flag=false;19   20   public synchronized void set(String names){21     while(flag)22       try {23         this.wait();//等待状态        24       } catch (InterruptedException e) {25         e.printStackTrace();26       }  27        this.name=names+"---"+this.No++;28        System.out.println(this.name+"---被"+Thread.currentThread().getName()+"生产");      29         flag=true;30         this.notifyAll();//唤醒所有线程31   }  32   public synchronized void out(){33     while(!flag)34       try {35         this.wait();//等待状态36       } catch (InterruptedException e) {37         e.printStackTrace();38       }    39     System.out.println(this.name+"---被"+Thread.currentThread().getName()+"消费了-------");    40        flag=false;41        this.notifyAll();//唤醒所有线程42   }43 }44 //生产者45 class Producter implements Runnable{46   private Product p;47   public Producter(Product pr){48     this.p=pr;49   }50   public void run(){    51    while(true){52     p.set("BMW");53    }54   }  55 }56 //消费者57 class Consumer implements Runnable{58   private Product p;59   public Consumer(Product pr){60     this.p=pr;61   }  62   public void run(){    63     while(true){64     p.out();65     }66   }67 }

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:黑马程序员系列第二篇 多线程(2)

关键词:线程

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。