博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
多线程--生产者消费者--简单例子
阅读量:4510 次
发布时间:2019-06-08

本文共 1679 字,大约阅读时间需要 5 分钟。

package com.lm.multest;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;class Resource {	private int num;	private String name;	private boolean flag = false;	Lock lock = new ReentrantLock();	Condition notFull = lock.newCondition();	Condition notEmpty = lock.newCondition();	public void set(String n) {		lock.lock();		try {			while (flag)				notFull.await();			this.name = n + num++;			System.out.println(Thread.currentThread().getName() + "..生产..."					+ name);			flag = true;			notEmpty.signalAll();		} catch (InterruptedException e) {			e.printStackTrace();		} finally {			lock.unlock();		}	}	public void out() {		lock.lock();		try {			while (!flag)				notEmpty.await();			System.out.println(Thread.currentThread().getName() + "..消费.."					+ name);			flag = false;			notFull.signalAll();		} catch (InterruptedException e) {			e.printStackTrace();		} finally {			lock.unlock();		}	}}class Producer implements Runnable {	private Resource res;	Producer(Resource res) {		this.res = res;	}	@Override	public void run() {		while (true)			res.set("商品");	}}class Consumer implements Runnable {	private Resource res;	Consumer(Resource res) {		this.res = res;	}	public void run() {		while (true)			res.out();	}}public class ProducerConsumerDemo {	public static void main(String[] args) {		Resource r = new Resource();		Producer p = new Producer(r);		Consumer c = new Consumer(r);		Thread th1 = new Thread(p);		Thread th2 = new Thread(c);		Thread th3 = new Thread(p);		Thread th4 = new Thread(c);		th1.start();		th2.start();		th3.start();		th4.start();	}}

转载于:https://www.cnblogs.com/james1207/p/3285785.html

你可能感兴趣的文章
[唐胡璐]Selenium技巧 - 定制元素属性检查,并写到ReportNG中
查看>>
hdu 1695 莫比乌斯基础题
查看>>
做题记录 To 2019.2.13
查看>>
Cg(C for Graphic)语言表达式与控制语句(转)
查看>>
C++中Static的作用
查看>>
一套完整的javascript面试题
查看>>
Centos7安装gitlab-ce
查看>>
centos7修改hostname
查看>>
正则表达式中的懒惰匹配与非捕获组
查看>>
Android 开发服务类 03_ServletForGETMethod
查看>>
一些基础名词及含义(更新中)
查看>>
sql索引优化 (从网上学习的时候总结的)
查看>>
Spring中配置数据源的4种形式
查看>>
Nuget 相关
查看>>
制作类似DataGrid自定义控件
查看>>
XML的解析和保存
查看>>
Mac使用git/github小结
查看>>
项目的质量管理活动与通行方法
查看>>
VS2010快捷键
查看>>
【转】CSS Nuggest
查看>>