public class TestSync implements Runnable {
Timer timer = new Timer();
public static void main(String[] args) {
TestSync test1 = new TestSync();
TestSync test2 = new TestSync();
Thread t1 = new Thread(test1);
Thread t2 = new Thread(test2);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run(){
timer.add(Thread.currentThread().getName());
}
}class Timer{
private static int num = 0;
public synchronized void add(String name){
//synchronized (this) {
num ++;
try {Thread.sleep(1);}
catch (InterruptedException e) {}
System.out.println(name+", 你是第"+num+"个使用timer的线程");
//}
}
}
-----------------------
输出结果:
t2, 你是第2个使用timer的线程
t1, 你是第2个使用timer的线程为什么是这样的结果?
Timer timer = new Timer();
public static void main(String[] args) {
TestSync test1 = new TestSync();
TestSync test2 = new TestSync();
Thread t1 = new Thread(test1);
Thread t2 = new Thread(test2);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run(){
timer.add(Thread.currentThread().getName());
}
}class Timer{
private static int num = 0;
public synchronized void add(String name){
//synchronized (this) {
num ++;
try {Thread.sleep(1);}
catch (InterruptedException e) {}
System.out.println(name+", 你是第"+num+"个使用timer的线程");
//}
}
}
-----------------------
输出结果:
t2, 你是第2个使用timer的线程
t1, 你是第2个使用timer的线程为什么是这样的结果?
System.out 前都已经执行了
num ++;
所以,到ssystem.out时,num成为2了,自然就是2了。当然,你输出的结果不是惟一的,在某些情况下输出结果会是你想要的1 和 2
可是方法不是已经被锁起来了吗?一个线程调用完add方法,另一个线程才有机会调用这个方法的啊。
TestSync test1 = new TestSync();
TestSync test2 = new TestSync();
你new了两个线程对象,Timer timer = new Timer();也等于new了两个,也就是说你的锁不是上在同一个对象里,失去了作用域。你的程序可以这样理解:t1执行num+1变成2进入休眠,t2执行,num+1变成2打印出来,t1再打印出来.我想结果也不是唯一的。
要实现同步的话,TestSync test1 = new TestSync();一个就OK了,两个THREAD里面都放test1。
TestSync test1 = new TestSync();
TestSync test2 = new TestSync();
Thread t1 = new Thread(test1); //t1锁的是test1.timer
Thread t2 = new Thread(test2); //t2锁的是test2.timer
因为锁的是不同的对象,所以不能保证同步,test1.timer和test2.timer分别进行num++,当执行到打印输出的时候,num就是不确定的了
TestSync test = new TestSync();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
private static int num = 0;
private static final Timer temp;
public synchronized void add(String name){
synchronized (temp) {
num ++;
}
try {Thread.sleep(1);}
catch (InterruptedException e) {}
System.out.println(name+", 你是第"+num+"个使用timer的线程");
}
}
class Timer{
private static int num = 0;
public void add(String name){
synchronized (Timer.class) {
num ++;
try {Thread.sleep(1);}
catch (InterruptedException e) {}
System.out.println(name+", 你是第"+num+"个使用timer的线程");
}
}
}