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();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值