A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区
传智教育官网黑马程序员官网
只需一步,快速开始
池中月
中级黑马
黑马币:-2
帖子:106
精华:0
© 池中月 中级黑马 / 2015-7-4 22:04 / 653 人查看 / 1 人回复 / 0 人收藏 转载请遵从CC协议 禁止商业使用本文
1、JDK5中提供多线程解决方案
示例:package unit18; import java.util.concurrent.locks.*; class Resources{ private String name; private int count = 1; private Boolean flag = false; private Lock lock = new ReentrantLock();//定义Lock类 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.wait();//生产者调用线程等待 } this.name = name+"__ " + count++; System.out.println(Thread.currentThread().getName()+ "......生产者" + this.name); flag = true; condition_con.signal(); //唤醒消费者线程 }catch(Exception e){} finally{ lock.unlock();//解锁 } } public void show()throws InterruptedException{ lock.lock(); try{ while(!flag){ condition_con.wait(); } System.out.println(Thread.currentThread().getName()+"消费者"+ this.name); flag = false; condition_pro.signal();//唤醒生产者线程 }catch(Exception e){} finally{ lock.unlock(); } } } class Producters implements Runnable{ private Resources r; Producters(Resources r){ this.r = r; } public void run(){ while(true){ try { r.set("商品"); } catch (InterruptedException e) { } } } } class Customers implements Runnable{ private Resources r; Customers(Resources r){ this.r = r; } public void run(){ while(true){ try { r.show(); } catch (InterruptedException e) { } } } } public class ProducterCustomerTest2 { public static void main(String[] args) { Resources r = new Resources(); Producters pro = new Producters(r); Customers cus = new Customers(r); Thread t1 = new Thread(pro); Thread t2 = new Thread(pro); Thread t3 = new Thread(cus); Thread t4 = new Thread(cus); t1.start(); t2.start(); t3.start(); t4.start(); } }复制代码