我有這個類,我在其中運行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();
}
}
請幫忙