我有线程睡眠问题。在线程运行方法内部,我有一个同步块和一个睡眠时间。
每个线程以 5 个单位递增或递减共享类“值”,然后休眠。
public class borr {
public static void main(String[] args) {
int times=5;
int sleeptime=1000;
int initial=50;
Shared shared = new Shared(initial);
ThreadClass tIncrement = new ThreadClass(shared,times,sleeptime,true);
ThreadClass tDecrement = new ThreadClass(shared,times,sleeptime,false);
tIncrement.start();
tDecrement.start();
}
}
class Shared{
int value=0;
public Shared(int value) {
super();
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
class ThreadClass extends Thread{
Shared shared;
int times=0;
int sleeptime=0;
boolean inc;
public ThreadClass(Shared shared, int times, int sleeptime, boolean inc) {
super();
this.shared = shared;
this.times = times;
this.sleeptime = sleeptime;
this.inc = inc;
}
public void run() {
int aux;
if(inc) {
for(int i=0;i<times;i++) {
synchronized(shared) {
aux=shared.getValue()+1;
shared.setValue(aux);
System.out.println("Increment, new value"+shared.getValue());
try {
Thread.sleep(sleeptime);
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
else {
for(int i=0;i<times;i++) {
synchronized(shared) {
aux=shared.getValue()-1;
shared.setValue(aux);
System.out.println("Decrement, new value"+shared.getValue());
try {
Thread.sleep(sleeptime);
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
}
}
但如果我移动Thread.sleep
出于synchronized
block,像这样,输出是递增,递减,递增,递减。当它停止休眠并开始新的循环迭代时,其他线程不应该尝试进入吗?相反,它继续循环直到该线程完成:
for(int i=0;i<times;i++) {
synchronized(shared) {
aux=shared.getValue()-1;
shared.setValue(aux);
System.out.println("Decrement, new value"+shared.getValue());
}
try {
Thread.sleep(sleeptime);
}catch(Exception e) {
e.printStackTrace();
}
}