编写一个应用程序,在主线程中创建三个线程:“运货司机”“装运工”“仓库管理员”。要求线程“运货司机”占有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[]{ 运货司机, 装运工, 仓库管理员 });
}
}