public class TestSync implements Runnable {
Timer timer = new Timer();
public static void main(String[] args) {
TestSync test = new TestSync();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
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 void add(String name){
synchronized (this) {
num ++;
try {Thread.sleep(100);}
catch (InterruptedException e) {}
System.out.println(name+", 你是第"+num+"个使用timer的线程");
}
synchronized (this) {
try {Thread.sleep(1000);}
catch (InterruptedException e) {}
System.out.println("sdfsdfklj");
}
}
}
它的输出结果是:
t1, 你是第1个使用timer的线程
t2, 你是第2个使用timer的线程
sdfsdfklj
sdfsdfklj
那么请问,t1,t2在调用public void add(String name)时的两个synchronized (this)它们的执行顺序是什么。
为什么它们不会形成死锁呢?
如果能在线给我解答最好,,非常感谢
Timer timer = new Timer();
public static void main(String[] args) {
TestSync test = new TestSync();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
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 void add(String name){
synchronized (this) {
num ++;
try {Thread.sleep(100);}
catch (InterruptedException e) {}
System.out.println(name+", 你是第"+num+"个使用timer的线程");
}
synchronized (this) {
try {Thread.sleep(1000);}
catch (InterruptedException e) {}
System.out.println("sdfsdfklj");
}
}
}
它的输出结果是:
t1, 你是第1个使用timer的线程
t2, 你是第2个使用timer的线程
sdfsdfklj
sdfsdfklj
那么请问,t1,t2在调用public void add(String name)时的两个synchronized (this)它们的执行顺序是什么。
为什么它们不会形成死锁呢?
如果能在线给我解答最好,,非常感谢
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货