我在该类中运行了10次for循环。此类实现Runnable接口(interface)。现在在main()中,我创建了2个线程。现在两者都将循环运行直到10。但是我想检查每个线程的循环计数。如果t1超过7,则使其 sleep 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();
}
}
请帮忙
最佳答案
我添加了一个同步块(synchronized block),一次只能由一个线程输入。两个线程都并行调用并输入方法。一线程将赢得比赛并获得锁定。第一个线程离开该块后,它将等待2秒。在这个时候,第二个线程可以遍历循环。我认为这种行为是通缉的。如果第二个线程也不能等待2秒,则可以设置一个 boolean 值标志,即第一个线程完成了该块,并在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();
}
}