利用管道实现线程间通信,看了考试的视频,在看了这个小代码,觉得对管道流的认识进一步加深了。小代码附上:
class Synchronous
{
public static void main(String[] args)
{
Resources res=new Resources();
Machinery one=new Machinery("no"+1,res);
Machinery two=new Machinery("no"+2,res);
Thread threadone=new Thread(one);
Thread threadtwo=new Thread(two);
threadone.start();
threadtwo.start();
try
{
threadone.join();
threadtwo.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Hello World!");
}
}
class Resources
{
public synchronized void Use(String No)
{
System.out.println(No+"正在使用资源");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(No+"释放资源");
}
}
class Machinery implements Runnable
{
Resources res;
String No;
Machinery(String No,Resources res)
{
this.No=No;
this.res=res;
}
public void run()
{
res.Use(No);
}
}
运行结果如下:
no1正在使用资源
no1释放资源
no2正在使用资源
no2释放资源
Hello World!
请按任意键继续. . .
|
|