`
whotodo
  • 浏览: 168517 次
文章分类
社区版块
存档分类
最新评论

Coordination between Threads

 
阅读更多

Every object in java has the methods wait()and notify():

wait() - make the thread that call thismethod to have a sleep until other thread call this object's notify()

notify() - notify the thread that iswaiting (it is the first one that begins to wait for this object) on thisobject’s monitor that it can continue now.


When we want to coordinate some threads' actions, we can use wait() and notify() method.The following code show the easiestusage of wait() and notify, and in this program, ThreadA needs ThreadB to let it go, or ThreadA will keep waiting for the oject's monitor.

package org.vhow.java.thread;

/**
 * The resource that may be accessed by the threads that need to coordinate
 * their actions.
 */
public class Data
{
	boolean go = false;

	public synchronized void makeWait() throws InterruptedException
	{
		while (!go)
		{
			System.out.println(Thread.currentThread() + " is waiting...");
			// Let the current thread to wait until another thread invokes this.notify()
			wait();
			System.out.println("done.");
		}
	}

	public synchronized void letGo()
	{
		go = true;
		
		// Wakes up a single thread is waiting on this object's monitor.
		notify();
	}
}

package org.vhow.java.thread;

public class ThreadA extends Thread
{
	Data data;
	
	public ThreadA(Data data)
	{
		this.data = data;
	}
	
	@Override
	public void run()
	{
		try
		{
			data.makeWait();
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
	}
}

package org.vhow.java.thread;

public class ThreadB extends Thread
{
	Data data;
	
	public ThreadB(Data data)
	{
		this.data = data;
	}
	
	@Override
	public void run()
	{
		data.letGo();
	}
}

package org.vhow.java.thread;

public class AppMain
{
	public static void main(String[] args) throws InterruptedException
	{
		// The resource that may accessed by ThreadA and ThreadB
		Data data = new Data();
		
		ThreadA threadA = new ThreadA(data);
		ThreadB threadB = new ThreadB(data);
		
		threadA.setName("thread-a");
		threadB.setName("thread-b");
		
		threadA.start();
		
		Thread.sleep(2000);
		
		threadB.start();
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics