本文包含两个代码示例,以演示Java并发性。它们代表非常典型的用法。通过了解它们,您将对notify()和wait()有更好的了解。
1.一些背景知识
1.synchronized 关键字用于独占访问。
2.要使方法同步,只需将synced关键字添加到其声明中即可。这样,对同一对象的同步方法的两次调用都不能相互交织。
3.同步语句必须指定提供内部锁的对象。使用synced(this)时,必须避免同步其他对象的方法的调用。
4.wait() 告诉调用线程放弃监视器并进入睡眠状态,直到其他线程进入同一监视器并调用notify()。
5.notify()唤醒调用wait()同一对象的第一个线程。
2. notify()和wait()-示例1
public class ThreadA {
public static void main(String[] args){
ThreadB b = new ThreadB();
b.start();
synchronized(b){
try{
System.out.println("Waiting for b to complete...");
b.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Total is: " + b.total);
}
}}
class ThreadB extends Thread{
int total;
@Override
public void run(){
synchronized(this){
for(int i=0; i<100 ; i++){
total += i;
}
notify();
}
}}
在上面的示例中,对象b已同步。b在主线程输出其总值之前完成计算。
输出:
Waiting for b to complete…
Total is: 4950
如果b没有像下面的代码那样同步:
public class ThreadA {
public static void main(String[] args) {
ThreadB b = new ThreadB();
b.start();
System.out.println("Total is: " + b.total);
}}
class ThreadB extends Thread {
int total;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
total += i;
}
}}
结果将为0、10等。因为sum在使用前尚未完成。
3. notify()和wait()-示例2
第二个示例更为复杂,请参见注释。
import java.util.Vector;
class Producer extends Thread {
static final int MAXQUEUE = 5;
private Vector messages = new Vector();
@Override
public void run() {
try {
while (true) {
putMessage();
//sleep(5000);
}
} catch (InterruptedException e) {
}
}
private synchronized void putMessage() throws InterruptedException {
while (messages.size() == MAXQUEUE) {
wait();
}
messages.addElement(new java.util.Date().toString());
System.out.println("put message");
notify();
//Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object.
}
// Called by Consumer
public synchronized String getMessage() throws InterruptedException {
notify();
while (messages.size() == 0) {
wait();//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
}
String message = (String) messages.firstElement();
messages.removeElement(message);
return message;
}}
class Consumer extends Thread {
Producer producer;
Consumer(Producer p) {
producer = p;
}
@Override
public void run() {
try {
while (true) {
String message = producer.getMessage();
System.out.println("Got message: " + message);
//sleep(200);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
Producer producer = new Producer();
producer.start();
new Consumer(producer).start();
}}
可能的输出顺序:
Got message: Fri Dec 02 21:37:21 EST 2011
put message
put message
put message
put message
put message
Got message: Fri Dec 02 21:37:21 EST 2011
Got message: Fri Dec 02 21:37:21 EST 2011
Got message: Fri Dec 02 21:37:21 EST 2011
Got message: Fri Dec 02 21:37:21 EST 2011
Got message: Fri Dec 02 21:37:21 EST 2011
put message
put message
put message
put message
put message
Got message: Fri Dec 02 21:37:21 EST 2011
Got message: Fri Dec 02 21:37:21 EST 2011
Got message: Fri Dec 02 21:37:21 EST 2011
最后,开发这么多年我也总结了一套学习Java的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。