This article contains two code examples to demonstrate Java concurrency. They stand for very typical usage. By understanding them, you will have a better understanding about notify() and wait().
1. Some background knowledge
a. synchronized keyword is used for exclusive accessing.
b. To make a method synchronized, simply add the synchronized keyword to its declaration. Then no two invocations of synchronized methods on the same object can interleave with each other.
c. Synchronized statements must specify the object that provides the intrinsic lock. When synchronized(this) is used, you have to avoid to synchronizing invocations of other objects’ methods.
d. wait() tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).
e. notify() wakes up the first thread that called wait() on the same object.
2. Notify and wait example 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();
}
}
}
In the example above, an object, b, is synchronized. b completes the calculation before Main thread outputs its total value.
Output:
Waiting for b to complete...
Total is: 4950
If b is not synchonized like the code below:
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;
}
}
}
The result would be 0, 10, etc. Because sum is not finished before it is used.
分享到:
相关推荐
wait和notify讲解
源码—Java多线程5—死锁和wait notify notifyAll
使用Java多线程的wait和notify方法实现最简单的生产者消费者模式
Java 同步方式 wait和notify/notifyall
一个简单的线程同步机制,也能实例了解wait notify的使用,notify与notifyAll的区别
java多线程之wait,notify的用法([ 详解+实例 ]).
java多线程下wait和notify的作用
开一个子线程来完成一个循环处理的工作,我在主线程中能灵活控制这个子线程的开始、暂停/继续、结束。
3(深入理解Wait、Notify和Wait与sleep区别).rar
在学习Java过程中,自己收集了很多的Java的学习资料,分享给大家,有需要的欢迎下载,希望对大家有用,一起学习,一起进步。
主线程去控制子线程wait与notify
java中多线程编程notify、wait的使用
Java多线程的样例代码,工程,内含wait()、notify()和sychronized的使用范例。
wait()、notify()和notifyAll()方法1---马克-to-win java视频
wait()、notify()和notifyAll()方法2---马克-to-win java视频
一个理解wait()与notify()的例子,让你更好理解.
wait, notify 和 notifyAll,这些在多线程中被经常用到的保留关键字,在实际开发的时候很多时候却并没有被大家重视。本文对这些关键字的使用进行了描述。 在 Java 中可以用 wait、notify 和 notifyAll 来实现...
主要介绍了java多线程wait,notify,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,下面小编和大家一起来学习一下吧
wait,notify等线程知识.pdf
JAVAWAIT和NOTIFY的用法.pdf