多线程经典之生产者与消费者
2016-07-06 10:02
585 查看
<strong>package PAndC; public class C { private Service service; public void eat(Service service) throws InterruptedException{ synchronized (service) { if(Service.restoreValue.equals("")){ service.wait(); } System.out.println("吃" + Service.restoreValue); Service.restoreValue = ""; service.notify(); } } } package PAndC; public class P { private Service service; public void create(Service service) throws InterruptedException{ synchronized (service) { if(!Service.restoreValue.equals("")){ service.wait(); } String time = System.currentTimeMillis() + ""; System.out.println("生产 " + time); service.restoreValue = time; service.notify(); } } } package PAndC; public class Service { public static String restoreValue = ""; } package PAndC; public class ThreadC extends Thread{ private C c; private Service service; public ThreadC(Service service, C c){ this.service = service; this.c = c; } public void run(){ while(true){ try { c.eat(service); } catch (InterruptedException e) { e.printStackTrace(); } } } } package PAndC; public class ThreadP extends Thread{ private Service service; private P p; public ThreadP(Service service, P p){ this.service = service; this.p = p; } public void run(){ while(true){ try { p.create(service); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } package PAndC; public class TestMain { public static void main(String[] args) throws InterruptedException { Service service = new Service(); P p = new P(); C c = new C(); ThreadC threadC = new ThreadC(service, c); threadC.start(); Thread.sleep(1000); ThreadP threadP = new ThreadP(service, p); threadP.start(); } } </strong>
<strong>没懂的问我下 wechat: wangyan199366</strong>
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- Python3写爬虫(四)多线程实现数据爬取
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序