Java并发 专题
您的位置:java > Java并发专题 > Java并发同步
Java并发同步
作者:--    发布时间:2019-11-20

下面是一个具有同步功能的多线程示例,这是和上篇文章同样的例子,它依次打印计数器值,每次运行它时,它产生相同的结果。

实例

class printdemo {
   public void printcount() {
      try {
         for(int i = 5; i > 0; i--) {
            system.out.println("counter   ---   "  + i );
         }
      }catch (exception e) {
         system.out.println("thread  interrupted.");
      }
   }
}

class threaddemo extends thread {
   private thread t;
   private string threadname;
   printdemo  pd;

   threaddemo( string name,  printdemo pd) {
      threadname = name;
      pd = pd;
   }

   public void run() {
      synchronized(pd) {
         pd.printcount();
      }
      system.out.println("thread " +  threadname + " exiting.");
   }

   public void start () {
      system.out.println("starting " +  threadname );
      if (t == null) {
         t = new thread (this, threadname);
         t.start ();
      }
   }
}

public class testthread {

   public static void main(string args[]) {
      printdemo pd = new printdemo();

      threaddemo t1 = new threaddemo( "thread - 1 ", pd );
      threaddemo t2 = new threaddemo( "thread - 2 ", pd );

      t1.start();
      t2.start();

      // wait for threads to end
      try {
         t1.join();
         t2.join();
      }catch( exception e) {
         system.out.println("interrupted");
      }
   }
}

每次运行此程序时都会产生相同的结果 -

starting thread - 1
starting thread - 2
counter   ---   5
counter   ---   4
counter   ---   3
counter   ---   2
counter   ---   1
thread thread - 1  exiting.
counter   ---   5
counter   ---   4
counter   ---   3
counter   ---   2
counter   ---   1
thread thread - 2  exiting.

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册