黑马程序员技术交流社区

标题: 利用管道实现线程间通信 [打印本页]

作者: stormdzh    时间: 2013-9-16 11:03
标题: 利用管道实现线程间通信
利用管道实现线程间通信,看了考试的视频,在看了这个小代码,觉得对管道流的认识进一步加深了。小代码附上:
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!
请按任意键继续. . .



作者: 645420297    时间: 2013-9-16 22:43
不错 不错




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2