public class Test3 {
public static void main(String[] args) {
computer3 t = new computer3();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}class computer3 extends Thread {
int i = 10;
static Object obj = new Object(); public void print() {
System.out.println(Thread.currentThread().getName() + ":" + i);
i--;
} public void run() {
while (i > 0) {
synchronized (obj) {
print();
}
try {
sleep(100);
} catch (Exception e) {
}
}
}
}程序如上,问题是,正常情况i只会显示到1的,但是多运行几次,会出现i为0,甚至是-1的情况,不知道是怎么回事?
public static void main(String[] args) {
computer3 t = new computer3();
new Thread(t).run();
new Thread(t).run();
new Thread(t).run();
}
}class computer3 extends Thread {
int i = 10;
public synchronized void print() {
System.out.println(Thread.currentThread().getName() + ":" + i);
i--;
} @Override
public void run() {
while(i > 0) {
print(); }
}
}
不要用 obj 作为锁 一个String 就够了
所以每个线程会sleep100ms后看i是否还是>0,而这时如果别的线程的i还没执行完print方法中的i--语句,而本线程的sleep时间已经到了之后,那么自然会执行到while()循环里面去,所以是你程序代码问题。
看看这个代码以及执行结果会方便你了解。public class Test3 {
public static void main(String[] args) {
computer3 t = new computer3();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}class computer3 extends Thread {
int i = 10;
static Object obj = new Object(); public void print() {
System.out.println(Thread.currentThread().getName() + ":" + i);
i--;
} public void run() {
while (i > 0) {
synchronized (this) {
print();
try {
sleep(100);
} catch (Exception e) {
}
}
}
}
}
synchronized (obj) {
改成
while (i > 0) {
synchronized (obj) {
if(i>0){ // 加上这个if吧,后面别忘了加上}
public static void main(String[] args) {
computer3 t = new computer3();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}class computer3 extends Thread {
int i = 10; public void print() {
System.out.println(Thread.currentThread().getName() + ":" + i);
i--;
} public void run() {
synchronized(this){
while (i > 0) {
print();
try {
sleep(100);
} catch (Exception e) {
}
}
}
}
}这样好像可以了...