专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »博文摘选 » java6:Java6学习笔记59——多线程编程——线程的同步(version 0.2) »正文

java6:Java6学习笔记59——多线程编程——线程的同步(version 0.2)

来源: 发布时间:星期二, 2009年10月6日 浏览:123次 评论:0

public class JoinDemo extends Object {
  public static Thread createThread(String name, long napTime) {
    final long sleepTime = napTime;

    Runnable r = new Runnable() {
        public void run() {
          try {
            print("in run() - entering");
            Thread.sleep(sleepTime);
          } catch ( InterruptedException x ) {
            print("interrupted!");
          } finally {
            print("in run() - leaving");
          }
        }
      };
 
    Thread t = new Thread(r, name);
    t.start();

    return t;
  }

  private static void print(String msg) {
    String name = Thread.currentThread().getName();//将打印的信息前边加上由哪个线程打印的出处信息。
    System.out.println(name + ": " + msg);
  }

  public static void main(String[] args) {
    Thread[] t = new Thread[3];
    /*创建了三个线程A、B、C,休眠时间分别为2s,1s,3s*/


    t[0] = createThread("thread A", 2000);
    t[1] = createThread("thread B", 1000);
    t[2] = createThread("thread C", 3000);

    for ( int i = 0; i < t.length; i++ ) {
      try {
        String idxStr = "thread[" + i + "]";
        String name = "[" + t[i].getName() + "]";

        print(idxStr + ".isAlive()=" +
            t[i].isAlive() + " " + name);
        print("about to do: " + idxStr +
            ".join() " + name);

        long start = System.currentTimeMillis();
        t[i].join(); // wait for the thread to die
        long stop = System.currentTimeMillis();

        print(idxStr + ".join() - took " +
            ( stop - start ) + " ms " + name);
      } catch ( InterruptedException x ) {
        print("interrupted waiting on #" + i);
      }
    }
  }
}

运行结果:

main: thread[0].isAlive()=true [thread A]//主线程判断线程A的状态
main: about to do: thread[0].join() [thread A]//主线程准备与 线程A同步
thread A: in run() - entering//三个线程依次启动
thread B: in run() - entering
thread C: in run() - entering
thread B: in run() - leaving//由于持续时间,B和A先结束
thread A: in run() - leaving
main: thread[0].join() - took 2003 ms [thread A]//主线程等待到了线程A,花费了2003ms
main: thread[1].isAlive()=false [thread B]//主线程判断线程B的状态
main: about to do: thread[1].join() [thread B]//主线程准备与 线程A同步
main: thread[1].join() - took 0 ms [thread B]//由于在同步前线层B已经结束了,所以当主线程等到B的时候其实是没有花费任何时间的。
main: thread[2].isAlive()=true [thread C]//主线程判断线程C的状态
main: about to do: thread[2].join() [thread C]//主线程准备与 线程C同步
thread C: in run() - leaving//线程C结束
main: thread[2].join() - took 1001 ms [thread C]//主线程等待到了线程C,花费了1001ms

0

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: