[英]How to slow a thread down in JAVA
我有這個類,我在其中運行10次for循環。 該類實現了Runnable接口。 現在在main()中我創建了2個線程。 現在兩個都將循環運行到10.但我想檢查每個線程的循環計數。 如果t1超過7,則讓它休眠1秒,以便讓t2完成。 但是如何實現這一目標呢? 請參閱代碼。 我嘗試但看起來完全愚蠢。 只是如何檢查一個線程的數據???
class SimpleJob implements Runnable {
int i;
public void run(){
for(i=0; i<10; i++){
System.out.println(Thread.currentThread().getName()+" Running ");
}
}
public int getCount(){
return i;
}
}
public class Threadings {
public static void main(String [] args){
SimpleJob sj = new SimpleJob();
Thread t1 = new Thread(sj);
Thread t2 = new Thread(sj);
t1.setName("T1");
t2.setName("T2");
t1.start();
try{
if(sj.getCount() > 8){ // I know this looks totally ridiculous, but then how to check variable i being incremented by each thread??
System.out.println("Here");
Thread.sleep(2000);
}
}catch(Exception e){
System.out.println(e);
}
t2.start();
}
}
請幫忙
您應該使用一些同步對象,而不是依賴於減慢線程。 我強烈建議你看一下java.util.concurrent包中的一個類。 您可以使用此CountdownLatch - 線程1將等待它,線程2將執行倒計時並釋放鎖定,並讓線程1繼續(釋放應在線程2代碼結束時完成)。
如果目標是並行運行2個Runnables(作為Threads)並等待它們兩者完成,你可以按照復雜性/功能的遞增順序:
編輯增加
首先,我不明白是什么魔法“如果你在7然后等待另一個”的邏輯就是這樣。 但是,要從主代碼中使用Thread.join(),代碼看起來就像
t1.start(); // Thread 1 starts running...
t2.start(); // Thread 2 starts running...
t1.join(); // wait for Thread 1 to finish
t2.join(); // wait for Thread 2 to finish
// from this point on Thread 1 and Thread 2 are completed...
我添加了一個synchronized塊,一次可以由一個線程輸入。 兩個線程都調用並輸入並行方法。 一個線程將贏得比賽並獲得鎖定。 在第一個線程離開塊后,它等待2秒。 在這個時候,第二個線程可以遍歷循環。 我認為這種行為是必要的。 如果第二個線程也不能等待2秒,你可以設置一些布爾標志,第一個線程完成塊並在if語句中使用這個標志,這可以防止第二個線程的等待時間。
class SimpleJob implements Runnable {
int i;
public void run(){
synchronized (this) {
for(i=0; i<8; i++){
System.out.println(Thread.currentThread().getName()+" Running ");
}
}
try {
System.out.println("Here");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(i=0; i<2; i++){
System.out.println(Thread.currentThread().getName()+" Running ");
}
}
public int getCount(){
return i;
}
}
public class Threadings {
public static void main(String [] args){
SimpleJob sj = new SimpleJob();
Thread t1 = new Thread(sj);
Thread t2 = new Thread(sj);
t1.setName("T1");
t2.setName("T2");
t1.start();
t2.start();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.