欢迎使用CSDN-markdown编辑器

java join方法控制多线程按照顺序执行

java中如果使用多线程时,如果不采取措施,代码的执行顺序往往不可控,如过使用join方法控制,则能实现线程的顺序执行:

#

public class CustomThread extends Thread{
String threadname;
Thread childThread;
int childPriority;//1,有限 0:不优先
public CustomThread(String threadname) {
super(threadname);
this.threadname=threadname;
}
public void setChildThread(Thread childThread,int priority){
this.childThread=childThread;
this.childPriority=priority;
}

 @Override
public void run() {

// String threadName = Thread.currentThread().getName();
System.out.println(threadname + ” start.”);
if(childThread!=null && childPriority==1){//子线程有限
try {
childThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
for (int i = 0; i < 5; i++) {
System.out.println(threadname + ” loop at ” + i);
Thread.sleep(1000);
}
System.out.println(threadname + ” end.”);
}
catch (Exception e) {
System.out.println(“Exception from ” + threadname + “.run”);
}

}

}

public class CunstomJoinTest {

/**
 * @param args
 * 过程:住想成就绪,t1就绪t2就绪,
 * t2获取cpu并执行,t2执行结束,
 * t1获取cpu并执行结束,
 * main继续执行
 */
public static void main(String[] args) {
    System.out.println("main start");
    CustomThread t1=new CustomThread("t1");
    CustomThread t2=new CustomThread("t2");
    t1.setChildThread(t2,1);//插入子线程,并且设置t2子线程优先
    t1.start();//就绪
    t2.start();//就绪

    try {
        t1.join();//在主线程中,设置t1子线程优先
        Thread.sleep(1000);
        System.out.println("main end");
    } catch (Exception e) {
    }

}

}

如果不适用join方法,代码的运行结果为:
main start
t2 start.
t2 loop at 0
t1 start.
t1 loop at 0
main end
t2 loop at 1
t1 loop at 1
t2 loop at 2
t1 loop at 2
t2 loop at 3
t1 loop at 3
t1 loop at 4
t2 loop at 4
t2 end.
t1 end.

或者

main start
t1 start.
t2 start.
t1 loop at 0
t2 loop at 0
main end
t2 loop at 1
t1 loop at 1
t2 loop at 2
t1 loop at 2
t1 loop at 3
t2 loop at 3
t1 loop at 4
t2 loop at 4
t1 end.
t2 end.

等各种情况

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值