首页 > PHP资讯 > JAVA培训 > 线程联合

线程联合

JAVA培训

线程联合:

一个线程A在占用CPU资源期间,可以让其它线程调用join()方法和本线程联合,B.join();称为A在运行期间联合的B。联合后A线程立刻中止执行,一直等到它联合的线程B执行完毕,线程A再重新排队等候。如果A准备联合的B已经结束,那么B.join()不会产生任何效果。

public class JoinThread implements Runnable {
       Thread threadA, threadB;
       String content[] = { "今天晚上", "大家不要", "回去得太早", "还有工作需要大家做!" };
       public JoinThread() {
              threadA = new Thread(this);
              threadB = new Thread(this);
              threadB.setName("经理");
       }
       public void run() {
              if (Thread.currentThread() == threadA) {
                     System.out.println("我等" + threadB.getName() + "说完我再说!");
                     try {
                            threadB.join();
                     } catch (Exception e) {
                            e.printStackTrace();
                     }
                     System.out.println("\n我开始说话了,我明白你的意思了,谢谢!");
              } else {
                     try {
                            System.out.println(threadB.getName() + "说:");
                            for (int i = 0; i < content.length; i++) {
                                   System.out.println(content[i]);
                                   threadB.sleep(1000);
                            }
                     } catch (Exception e) {
                            e.printStackTrace();
                     }
              }
       }
}
public class TestJoinThread {
       public TestJoinThread() {
       }
       public static void main(String[] args) {
              JoinThread test = new JoinThread();
              test.threadA.start();
              test.threadB.start();
       }
}

常州java培训机构

本文由欣才IT学院整理发布,未经许可,禁止转载。