主题:[讨论]synchronized线程同步的问题
书上说:“synchronized关键字指出方法一次只能被一个线程访问”,但是我在执行下面程序的时候发下add方法是每间隔5秒被调用两次,我的想法是t1执行add方法需要睡眠5秒钟,t2执行add方法也需要睡眠5秒钟,在此期间其它线程应该不能调用add方法,这样才和书上所说的一致,请问这种现象该如何解释那?
public class TestSynchronized extends Thread {
int count;
public static void main(String[] args) {
TestSynchronized t1 = new TestSynchronized();
t1.start();
TestSynchronized t2 = new TestSynchronized();
t2.start();
}
public void run() {
while(true){
add();
}
}
synchronized void add() {
count++;
System.out.println(count);
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class TestSynchronized extends Thread {
int count;
public static void main(String[] args) {
TestSynchronized t1 = new TestSynchronized();
t1.start();
TestSynchronized t2 = new TestSynchronized();
t2.start();
}
public void run() {
while(true){
add();
}
}
synchronized void add() {
count++;
System.out.println(count);
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}