public class Tsynchronized implements Runnable {
Integer b = 100;
public void m1() {
System.out.println("m_one:"+b);
synchronized(this){
b = 1000;
System.out.println("m_two:"+b);
}
try {
Thread.sleep(1500);
} catch (InterruptedException e) {}
System.out.println("m1:" + "b = " + b);
}
public void m2()throws Exception {
synchronized(this){
b = 2000;
Thread.sleep(1000);
}
System.out.println("m2:" + b);
}
public void run() {
m1();
} public static void main(String[] args)throws Exception {
Tsynchronized ts = new Tsynchronized();
Thread t = new Thread(ts);
t.start();
ts.m2();
}
}两个方法中都有锁,那怎样确定先调用哪一个方法,然后锁中的变量怎样确定。
Integer b = 100;
public void m1() {
System.out.println("m_one:"+b);
synchronized(this){
b = 1000;
System.out.println("m_two:"+b);
}
try {
Thread.sleep(1500);
} catch (InterruptedException e) {}
System.out.println("m1:" + "b = " + b);
}
public void m2()throws Exception {
synchronized(this){
b = 2000;
Thread.sleep(1000);
}
System.out.println("m2:" + b);
}
public void run() {
m1();
} public static void main(String[] args)throws Exception {
Tsynchronized ts = new Tsynchronized();
Thread t = new Thread(ts);
t.start();
ts.m2();
}
}两个方法中都有锁,那怎样确定先调用哪一个方法,然后锁中的变量怎样确定。
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货