JAVA学习笔记(四十二)-生产者消费者模型
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了JAVA学习笔记(四十二)-生产者消费者模型,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2627字,纯文字阅读大概需要4分钟。
内容图文
![JAVA学习笔记(四十二)-生产者消费者模型](/upload/InfoBanner/zyjiaocheng/1116/a2a540ffb7de42d588803af2b1ec1234.jpg)
wait()、notify()
/*
* wait()、notify()
*
* 1.两个方法都只能在synchronized代码块中执行,因为要对持有锁的线程操作,只有同步中才有锁
* 2.两个方法在操作同步中的线程时,必须要标识所操作线程持有的对象锁
* 3.等待和唤醒必须是同一个对象锁
*/
public
class
Test05 {
public
static
void main(String[] args) {
MyThread3 mt=new MyThread3();
Thread th=new Thread(mt,"线程一");
th.start();
try {
Thread.sleep(2000);//主线程休眠2秒,让线程th在等待池中待一会
} catch (InterruptedException e) {
e.printStackTrace();
}
//打断处于mt对象的等待池中的线程th//th.interrupt();
synchronized (mt) {
mt.notify();//唤醒对象mt的等待池中的一个线程
}
}
}
classMyThread3implementsRunnable{
@Override
publicvoid run() {
//同步代码块
synchronized (this) {
System.out.println("***进入同步代码块");
try {
wait();//线程进入wait池,处于阻塞状态
System.out.println("***wait之后重新拿到了锁");
} catch (InterruptedException e) {
System.out.println("***"+Thread.currentThread().getName()+"被打断!");
}
for(int i=1;i<=20;i++){
System.out.println(Thread.currentThread().getName()+"***"+i);
}
System.out.println("***同步代码块执行结束!");
}
}
}
生产者、消费者模型
/*
* 线程间通信:多个线程操作同一个资源,但操作的动作不同
* 生产者、消费者模型
* wait()和notify()方法一般应用于生产者和消费者模型中,用来等待同步数据
*/
public
class
Test06 {
public
static
void main(String[] args) {
Person person = new Person();
Input in = new Input(person);
Output out = new Output(person);
Thread th1 = new Thread(in,"生产者生产了: ");// 产生人
Thread th2 = new Thread(out,"消费者消费了: ");// 取出人
th1.start();
th2.start();
}
}
classPerson {
String name;
String sex;
boolean flag = true;// true表示需要产生人,false表示取出人
}
// 生产、入classInputimplementsRunnable {private Person person;
public Input(Person person) {
this.person = person;
}
@Override
publicvoid run() {
int x = 0;
while (true) {
synchronized (person) {
if (person.flag) {
if (x == 0) {// 判断间隔产生不同的人
person.name = "tom";
person.sex = "male";
} else {
person.name = "张三";
person.sex = "女";
}
x = (x + 1) % 2; // 间隔产生不同的人
person.flag = false;// 放一次,取一次
person.notify();//唤醒取人的线程
} else {
try {
person.wait();// 如果不需要产生人,则等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
// 消费、出classOutputimplementsRunnable {private Person person;
public Output(Person person) {
this.person = person;
}
@Override
publicvoid run() {
while (true) {
synchronized (person) {
if (!person.flag) {
System.out.println(Thread.currentThread().getName()+person.name + "***" + person.sex);
person.flag = true;
person.notify();//唤醒生产人的线程
} else {
try {
person.wait();//如果不需要取出人,则等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
原文:http://blog.csdn.net/wangzi11322/article/details/44737597
内容总结
以上是互联网集市为您收集整理的JAVA学习笔记(四十二)-生产者消费者模型全部内容,希望文章能够帮你解决JAVA学习笔记(四十二)-生产者消费者模型所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。