Java: Use wait () and notify () to implement inter-thread collaboration

Source: Internet
Author: User

From: http://zhangjunhd.blog.51cto.com/113473/71387

Using wait () and notify ()/notifyAll () allows multiple tasks to collaborate with each other. 1. wait () and Policy ()/policyall ()When sleep () and yield () are called, the lock is not released, and wait () is called to release the lock. In this way, another task (thread) can obtain the lock of the current object and enter its synchronized method. You can resume execution from wait () through notify ()/notifyAll (), or the expiration time. Wait (), Policy (), and policyall () can only be called in the synchronous control method or synchronization block (). If you call these methods in non-synchronous methods, the IllegalMonitorStateException will be thrown at runtime. 2. simulate a single thread to wake up multiple threadsSimulate collaboration between threads. The Game class has two Synchronization Methods: prepare () and go (). The flag start is used to determine whether the current thread needs wait (). A Game instance first starts all Athele instances to enter the wait () state. After a period of time, it changes the flag and calls all () All Athele threads in the wait state. Game. javaPackage concurrency;

Import java. util. Collection;
Import java. util. Collections;
Import java. util. HashSet;
Import java. util. Iterator;
Import java. util. Set;

Class Athlete implements Runnable {
Private final int id;
Private Game;

Public Athlete (int id, Game game ){
This. id = id;
This. game = game;
}

Public boolean equals (Object o ){
If (! (O instanceof Athlete ))
Return false;
Athlete athlete = (Athlete) o;
Return id = athlete. id;
}

Public String toString (){
Return "Athlete <" + id + "> ";
}

Public int hashCode (){
Return new Integer (id). hashCode ();
}

Public void run (){
Try {
Game. prepare (this );
} Catch (InterruptedException e ){
System. out. println (this + "quit the game ");
}
}
}

Public class Game implements Runnable {
Private Set <Athlete> players = new HashSet <Athlete> ();
Private boolean start = false;

Public void addPlayer (Athlete one ){
Players. add (one );
}

Public void removePlayer (Athlete one ){
Players. remove (one );
}

Public Collection <Athlete> getPlayers (){
Return Collections. unmodifiableSet (players );
}

Public void prepare (Athlete athlete) throws InterruptedException {
System. out. println (athlete + "ready! ");
Synchronized (this ){
While (! Start)
Wait ();
If (start)
System. out. println (athlete + "go! ");
}
}

Public synchronized void go (){
Policyall ();
}

Public void ready (){
Iterator <Athlete> iter = getPlayers (). iterator ();
While (iter. hasNext ())
New Thread (iter. next (). start ();
}

Public void run (){
Start = false;
System. out. println ("Ready ......");
System. out. println ("Ready ......");
System. out. println ("Ready ......");
Ready ();
Start = true;
System. out. println ("Go! ");
Go ();
}

Public static void main (String [] args ){
Game = new game ();
For (INT I = 0; I <10; I ++)
Game. addplayer (new athlete (I, game ));
New thread (game). Start ();
}
}

Result:
Ready ......
Ready ......
Ready ......
Athlete <0> ready!
Athlete <1> ready!
Athlete <2> ready!
Athlete <3> ready!
Athlete <4> ready!
Athlete <5> ready!
Athlete <6> ready!
Athlete <7> ready!
Athlete <8> ready!
Athlete <9> ready!
Go!
Athlete <9> go!
Athlete <8> go!
Athlete <7> go!
Athlete <6> go!
Athlete <5> go!
Athlete <4> go!
Athlete <3> go!
Athlete <2> go!
Athlete <1> go!
Athlete <0> go!
3. Simulate the busy waiting processAn instance of the MyObject class is an observer. When an event is observed, it notifies an instance of the Monitor class (by changing a flag ). However, this Monitor instance constantly checks whether the flag bit is changed by waiting for a long time.BusyWaiting. javaImport java. util. concurrent. TimeUnit;

Class MyObject implements Runnable {
Private Monitor monitor;

Public MyObject (Monitor monitor ){
This. monitor = monitor;
}

Public void run (){
Try {
TimeUnit. SECONDS. sleep (3 );
System. out. println ("I'm going .");
Monitor. gotMessage ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}

Class Monitor implements Runnable {
Private volatile boolean go = false;

Public void gotMessage () throws InterruptedException {
Go = true;
}

Public void watching (){
While (go = false)
;
System. out. println ("He has gone .");
}

Public void run (){
Watching ();
}
}

Public class BusyWaiting {
Public static void main (String [] args ){
Monitor monitor = new Monitor ();
MyObject o = new MyObject (monitor );
New Thread (o). start ();
New Thread (monitor). start ();
}
}

Result:
I'm going. He has gone.4. Use wait () and Policy () to rewrite the above exampleThe following example uses wait () to replace the busy wait mechanism. When a notification is received, notify is the current Monitor thread.Wait. javaPackage concurrency. wait;

Import java. util. concurrent. TimeUnit;

Class MyObject implements Runnable {
Private Monitor monitor;

Public MyObject (Monitor monitor ){
This. monitor = monitor;
}

Public void run (){
Try {
TimeUnit. SECONDS. sleep (3 );
System. out. println ("I'm going .");
Monitor. gotMessage ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}

Class Monitor implements Runnable {
Private volatile boolean go = false;

Public synchronized void gotMessage () throws InterruptedException {
Go = true;
Notify ();
}

Public synchronized void watching () throws InterruptedException {
While (go = false)
Wait ();
System. out. println ("He has gone .");
}

Public void run (){
Try {
Watching ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}

Public class Wait {
Public static void main (String [] args ){
Monitor monitor = new Monitor ();
MyObject o = new MyObject (monitor );
New Thread (o). start ();
New Thread (monitor). start ();
}
}

Result:
I'm going. He has gone.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.