我有两个线程:C和D。如果我要先执行线程C,然后再执行线程D,那是我必须要做的:
这是课程的代码ThreadC
:
public class ThreadC implements Runnable {
int isi[] = new int[100];
public void run () {
for (int i = 0;i < isi.length; i++) {
isi[i] = i;
System.out.print(isi[i] + " ");
}
}
}
这是课程的代码ThreadD
:
public class ThreadD implements Runnable {
int temp=0;
public void run () {
for(int i = 0; i < 1000; i++)
temp += i;
System.out.println("nilai temp : " + temp);
}
}
这是主要方法:
public class main {
public static void main (String[] args) {
ThreadC tc = new ThreadC();
Thread t1 = new Thread(tc);
t1.start();
ThreadD td = new ThreadD();
Thread t2 = new Thread(td);
t2.start();
}
}
编辑:
我实际上有问题,就是我上课。首先,我称ThreadC。我希望线程C完成执行,然后for下的线程将被执行。然后我叫ThreadD。就像下面的代码:
for (int j = 0; j < idW.length; j++) {
webtext = d.getWebText(idW[j]);
ThreadPrepo tpo = new ThreadPrepo(webtext, host[j%jumhost], "server", 1099, idW[j]);
Thread t1 = new Thread(tpo);
t1.start();
}
ThreadD td = new ThreadD;
Thread t2 = new Thread(t2);
t2.start();
因此ThreadD t2将在线程t1完成执行后执行,因此线程t2必须等待直到t1哈希完成。
我该如何解决?
使用Thread.join()。加入线程将等待它完成。如果要t2
在之后运行t1
,以下代码段将执行此操作:
t1.start();
t1.join(); // blocks until t1 is complete
t2.start();
编辑:澄清一下,如果您真的只有两个这样的线程,请不要这样做-不需要线程,并且可运行对象只能按顺序运行。如果您有多个线程同时运行,并且在运行其他代码之前需要等待所有线程完成,则联接可以很好地工作(线程完成后的代码不需要在线程中运行)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句