JAVA线程锁定的问题,请高人指点

来源:百度知道 编辑:UC知道 时间:2024/05/26 07:00:49
我遇到一道题,有关线程的,目的是输出下面的结果:

t1,你是第1个使用timer的线程.
t2,你是第2个使用timer的线程.

但是我得到的结果是
t1,你是第2个使用timer的线程.
t2,你是第2个使用timer的线程.

以下是我的代码,我明明用了Synchronized,,为什么还会出现这个问题.

public class TestSync {
public static void main(String[] args) {
Timer t1 = new Timer("t1");
Timer t2 = new Timer("t2");
t1.start();
t2.start();
}
}

class Timer extends Thread {
static int num = 0;
Timer(String s) {
super(s);
}
public void run() {
synchronized(this) {
num ++;
try {
sleep(1);
} catch (InterruptedException e) {
System.out.println("对不起,有错误发生");
}
System.out.println(getName()+", 你是第"+num+"个使用Timer的线程");
}
}
}

你两个线程加锁的分别是两个不同的对象 所以等于没有加锁

//正确代码:

public class TestSync implements Runnable {
static int num = 0;
public void run(){
synchronized(this) {
num ++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
System.out.println("对不起,有错误发生");
}
System.out.println(Thread.currentThread().getName()+", 你是第"+num+"个使用Timer的

线程");
}
}
public static void main(String[] args) {
TestSync test = new TestSync();
Timer t1 = new Timer(test,"t1");
Timer t2 = new Timer(test,"t2");
t1.start();
t2.start();
}
}

class Timer extends Thread {
Timer(TestSync t,String s){
super(t,s);
}
}