我有兩個線程: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完成執行,然後線程將執行。然後我打電話給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哈希完成。
我該如何解決這個問題?
如果它是'Runnable',則不要將其稱爲線程。在你的兩個'Runnable'實例之間同步你的'run()'方法代碼。第一個輸入塊將首先執行並完成。 –
爲什麼大家試圖用線程做的第一件事就是首先破壞線程的整個觀點? –
我從來不理解這些問題。如果你想順序執行,爲什麼你使用線程呢? – EJP