ThreadJoinTest

来源:互联网 发布:广州入学积分怎么算法 编辑:程序博客网 时间:2024/06/15 18:30

package org.sf.thread;
/**
 *  线程join
 * ,当主线程处理完其他的事务后,需要用到子线程的处理结果,这个时候就要用到join();方法了。
 *
 */
public class ThreadJoinTest {

 private int counter;
public class ThreadTesterA implements Runnable {
 @Override
 public void run() {
  while (counter <= 10) {
   System.out.print("Counter = " + counter + " ");
   counter++;
  }
  System.out.println();
 }
}

class ThreadTesterB implements Runnable {

 private int i;

 @Override
 public void run() {
  while (i <= 10) {
   System.out.print("i = " + i + " ");
   i++;
  }
  System.out.println();
 }
}
public void init() throws InterruptedException{
 Thread t1 = new Thread(new ThreadTesterA());
 Thread t2 = new Thread(new ThreadTesterB());
 t1.start();
 t1.join(); // wait t1 to be finished
 t2.start();
 t2.join(); // in this program, this may be removed
}

 public static void main(String[] args) throws InterruptedException {
  new ThreadJoinTest().init();
 }
}

0 0
原创粉丝点击