您的位置:首页 > 编程语言 > Java开发

java线程wait,notify,yield,join方法

2015-12-02 13:27 671 查看
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;

}

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: