欢迎使用CSDN-markdown编辑器

来源:互联网 发布:工行黄金交易软件 编辑:程序博客网 时间:2024/06/07 13:51

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;
}

 @Overridepublic 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
原创粉丝点击