public class NotifyAndWait {
private static final Object obj = new Object();
public static int flag = 0;
/**
* @param args
*/
public static void main(String[] args) {
T1 t1 = new T1();
T2 t2 = new T2();
T3 t3 = new T3();
new Thread(t1).start();
new Thread(t2).start();
new Thread(t3).start();
}
static class T1 implements Runnable {
@Override
public void run() {
synchronized (obj) {
try {
System.out.println("T1线程开始等待");
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("接收T2通知,T1线程开始执行任务");
System.out.println("现在的Flag是: " + flag);
try {
System.out.println("T1进入休眠2秒钟");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("wait、notify的使用在于同步资源对象的调用" + "及资源本身的同步");
System.out.println("End thanks !!!");
}
}
}
static class T2 implements Runnable {
boolean stop = true;
@Override
public void run() {
System.out.println("T2线程开始运作");
while (stop) {
synchronized (obj) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
++flag;
if (flag == 10) {
System.out.println("标志已经是10");
obj.notify();
Thread current = Thread.currentThread();
if (!current.isInterrupted()) {
try {
stop = false;
System.out.println("T2线程已经被停止");
if (stop)
current.interrupt();
} catch (Exception e) {
System.out.println("T2线程已经被打断终结");
}
}
}
}
}
}
}
}
class T3 implements Runnable {
long start = 0l;
boolean stop = true;
public T3() {
System.out.println("T3线程已经被实例化");
start = System.currentTimeMillis();
}
@Override
public void run() {
while (stop) {
if (System.currentTimeMillis() - start > 20000) {
stop = false;
}
//System.out.println("T3 run 方法执行");
if (NotifyAndWait.flag == 10) {
try {
//System.out.println("T3线程 run joining ...");
System.out.println("T3线程执行Join任务,开始执行代码");
Thread.currentThread().join();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
//System.out.println("T3线程 run yielding ...");
Thread.yield();
}
/*
* 执行join方法,开始下面任务的执行
*/
System.out.println("T3线程开始运作,T3线程即将停止");
stop = false;
}
}
}
java线程wait,notify,yield,join方法
于 2015-12-02 13:27:49 首次发布
本文通过一个Java示例展示了如何使用wait和notify方法来实现线程间的同步操作。示例中包括三个线程:T1等待信号后执行任务;T2负责计数并在达到特定值时发送信号;T3则在条件满足时尝试执行特定任务。

2344

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



