public class T0501_TestSync implements Runnable {
Timer timer = new Timer(); public void run() {
timer.add(Thread.currentThread().getName());
} public static void main(String[] args) {
T0501_TestSync test = new T0501_TestSync();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}}class Timer {
private static int num = 0; public synchronized void add(String name) {
num++;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
System.out.println(name + ", 你是第" + num + "个使用timer的线程");
}
}因为没有加锁,这个程序的输出应该是
t1, 你是第2个使用timer的线程
t2, 你是第2个使用timer的线程
但是,实际情况是这样的
t1, 你是第1个使用timer的线程
t2, 你是第2个使用timer的线程
高手解惑,多谢!!!
Timer timer = new Timer(); public void run() {
timer.add(Thread.currentThread().getName());
} public static void main(String[] args) {
T0501_TestSync test = new T0501_TestSync();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}}class Timer {
private static int num = 0; public synchronized void add(String name) {
num++;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
System.out.println(name + ", 你是第" + num + "个使用timer的线程");
}
}因为没有加锁,这个程序的输出应该是
t1, 你是第2个使用timer的线程
t2, 你是第2个使用timer的线程
但是,实际情况是这样的
t1, 你是第1个使用timer的线程
t2, 你是第2个使用timer的线程
高手解惑,多谢!!!
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货