聯合線程

編寫一個應用程序,在主線程中創建三個線程:“運貨司機”“裝運工”“倉庫管理員”。要求線程“運貨司機”佔有CPU資源後立刻聯合線程“裝運工”,而“裝運工”佔有資源後立刻聯合線程“倉庫管理員”,打開倉庫搬運貨物,然後裝成,運走。

package Tread;

public class Kyo implements Runnable
{
	public void start(String[] names)
	{
		if(null == threads)
		{
			threads = new Thread[3];
		}
		for(int i = 0; i < threads.length; i++)
		{
			Thread thread = threads[i];
			if(null == thread)
			{
				threads[i] = new Thread(this, names[i]);
				threads[i].setPriority(Thread.MIN_PRIORITY);
				threads[i].start();
			}
		}
	}

	public synchronized void stop(String name)
	{
		if(null != threads)
		{
			for(int i = 0; i < threads.length; i++)
			{
				Thread thread = threads[i];
				if(null != thread && name.equals(thread.getName()))
				{
					threads[i].interrupt();
					threads[i] = null;
					notifyAll();
					break;
				}
			}
		}
	}

	@Override
	public void run()
	{
		Thread current = Thread.currentThread();
		while(current.isAlive())
		{
			if(開車)
			{
				System.out.println("全部完成");
				break;
			}
			try
			{
				Thread.sleep(600);
			}
			catch(InterruptedException e)
			{
				break;
			}
			String name = current.getName();
			if(運貨司機.equals(name))
			{
				if(完成工作)
				{
					System.out.println("“裝運工”完成工作開始開車");
					開車 = true;
					stop(運貨司機);
				}
				else
				{
					System.out.println("“運貨司機”在等搬運工完成工作...");
				}
			}
			else if(裝運工.equals(name))
			{
				if(開始搬運貨物)
				{
					完成工作 = true;
					stop(裝運工);
				}
				if(打開倉庫)
				{
					System.out.println("“裝運工”開始搬運貨物");
					開始搬運貨物 = true;
				}
				else
				{
					System.out.println("“裝運工”在等倉庫管理員打開倉庫...");
				}
			}
			else if(倉庫管理員.equals(name))
			{
				System.out.println("“倉庫管理員”打開倉庫");
				打開倉庫 = true;
				stop(倉庫管理員);
			}
		}
	}

	private static final String 運貨司機 = "運貨司機";

	private static final String 裝運工 = "裝運工";

	private static final String 倉庫管理員 = "倉庫管理員";

	Thread[] threads;

	boolean 打開倉庫 = false;

	boolean 開始搬運貨物 = false;

	boolean 完成工作 = false;

	boolean 開車 = false;

	public static void main(String[] args)
	{
		new Kyo().start(new String[]{ 運貨司機, 裝運工, 倉庫管理員 });
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章