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

JavaSE 线程通信 wait() notify()

2014-04-21 02:14 471 查看
wait() 和notify()都是Object类的方法,实现thread和另外thread的通信。

主要要点:

一、当thread执行了wait()方法时,会释放掉它所持的对象锁,进入到wait pool中等待,等待被其他线程notify()后进入到lock pool中等待。在lock pool中获得对象锁后,继续从wait()的下一句执行。

二、notify()和wait()都在synchronized中。

三、wait()和sleep()的区别:

a) sleep()是Thread类的函数,wait()是所有类的对象都能obj,wait() 

b) sleep()不释放对象锁,休眠若干毫秒后醒来继续执行;wait()会释放掉对象锁,it will lose ownership of lock. 

实例:

用wait()和notify()实现4个threads之间的通信。 保证在0和1之间切换,当numberCount为0时,某线程+1操作,变为1; 当numberCount为1时,某线程-1操作,变为0.。。。。。一直在0、1之间跳转,不能跳到-1或2. 实例如下:

package com.syncronized.java;

public class TestNofity {

public static void main(String[] args) {

Example ex = new Example();

ThreadIncrase thIn_1 = new ThreadIncrase(ex);
ThreadIncrase thIn_2 = new ThreadIncrase(ex);

ThreadDecrease thDe_1 = new ThreadDecrease(ex);
ThreadDecrease thDe_2 = new ThreadDecrease(ex);

thIn_1.start();
thIn_2.start();
thDe_1.start();
thDe_2.start();

}
}

class Example {
private int numberCount;

public synchronized void increase() {
while(numberCount != 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (numberCount == 0) {
numberCount++;
System.out.println(numberCount);
}
this.notify();

}

public synchronized void decrease() {
while(numberCount == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

numberCount--;
System.out.println(numberCount);

this.notify();

}

}

class ThreadIncrase extends Thread {
private Example example;

public ThreadIncrase(Example exam) {
example = exam;
}

@Override
public void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep((long) (1000 * Math.random()));
} catch (InterruptedException e) {
e.printStackTrace();
}
example.increase();
}
}
}

class ThreadDecrease extends Thread {
private Example example;

public ThreadDecrease(Example exam) {
example = exam;
}

@Override
public void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep((long) (1000 * Math.random()));
} catch (InterruptedException e) {

e.printStackTrace();
}

example.decrease();
}
}
}

输出:
1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

0

1

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