package demo.thread;
/*
等待/唤醒机制。
涉及的方法:
1,wait(): 让线程处于冻结状态,被wait的线程会被存储到线程池(等待集)中。
2,notify():唤醒线程池中一个线程(任意).
3,notifyAll():唤醒线程池中的所有线程。
这些方法都必须定义在同步中。
因为这些方法是用于操作线程状态的方法。
必须要明确到底操作的是哪个锁上的线程。
为什么操作线程的方法wait notify notifyAll定义在了Object类中?
因为这些方法是监视器的方法。监视器其实就是锁。
锁可以是任意的对象,任意的对象调用的方式一定定义在Object类中。
*/
class Resource2 {
private String name;
private String sex;
private boolean flag = false;
synchronized void set(String name, String sex) {
if (flag == true)
try {
this.wait();
} catch (InterruptedException e) {
}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
synchronized void out() {
if (flag == false)
try {
this.wait();
} catch (InterruptedException e) {
}
System.out.println(name + "......." + sex);
flag = false;
notify();
}
}
//输入
class Input2 implements Runnable {
Resource2 r;
// Object obj = new Object();
Input2(Resource2 r) {
this.r = r;
}
public void run() {
int x = 0;
while (true) {
if (x == 0) {
r.set("mike", "nan");
} else {
r.set("丽丽", "女女女女女女");
}
x = (x + 1) % 2;
}
}
}
//输出
class Output2 implements Runnable {
Resource2 r;
// Object obj = new Object();
Output2(Resource2 r) {
this.r = r;
}
public void run() {
while (true) {
r.out();
}
}
}
class ResourceDemo3 {
public static void main(String[] args) {
//创建资源。
Resource2 r = new Resource2();
//创建任务。
Input2 in = new Input2(r);
Output2 out = new Output2(r);
//创建线程,执行路径。
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
//开启线程
t1.start();
t2.start();
}
}
多线程间的等待唤醒简单理解2
最新推荐文章于 2024-08-21 16:50:39 发布
本文详细介绍了Java中线程间的等待/唤醒机制,包括wait(), notify()和notifyAll()等方法的使用,并通过实例演示了如何实现线程间的数据传递与同步。
160

被折叠的 条评论
为什么被折叠?



