我有这个类,我在其中运行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();
}
}
请帮忙