麻烦大家看一下下边的程序片断的输出为什么是in thread 2 maple
in thread 1 maple我在两个线程里都用sychronized把a锁掉了阿,为什么会出现并发访问的问题,难道sleep()会释放对象锁??
public class ThreadTest { static String a = ""; public static void main(String[] args) { Thread thread1 = new Thread() { public void run() { synchronized (a) { a = "lincoln"; try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("in thread 1 " + a);
} } }; Thread thread2 = new Thread() { public void run() { synchronized (a) { a = "maple"; try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("in thread 2 " + a); } } }; thread1.start(); thread2.start(); }}
in thread 1 maple我在两个线程里都用sychronized把a锁掉了阿,为什么会出现并发访问的问题,难道sleep()会释放对象锁??
public class ThreadTest { static String a = ""; public static void main(String[] args) { Thread thread1 = new Thread() { public void run() { synchronized (a) { a = "lincoln"; try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("in thread 1 " + a);
} } }; Thread thread2 = new Thread() { public void run() { synchronized (a) { a = "maple"; try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("in thread 2 " + a); } } }; thread1.start(); thread2.start(); }}
但是 a = "lincoln"; 这一句后
线程2的锁对象成了 lincoln 这两个线程 不是公用一个锁 所以出现以上情况你可以把两个同步语句 改成这样 就可以得到你要的结果了 synchronized("")
拿到后 把 a = "lincoln"
于是第二个线程拿到的锁是 "lincoln"
不是一个锁,所以两个线程并没互斥
static String b = ""; public static void main(String[] args) {
Thread thread1 = new Thread() {
public void run() { synchronized (b) { a = "lincoln";
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} System.out.println("in thread 1 " + a);
}
}
}; Thread thread2 = new Thread() {
public void run() { synchronized (b) {
a = "maple";
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} System.out.println("in thread 2 " + a);
} }
}; thread1.start(); thread2.start();
}}
synchronized ("")是这样锁 肯定是 值 不是引用
in thread 2 maple
我这里运行的结果是in thread 1 lincoln
in thread 2 maple是不是你要的结果
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} System.out.println("in thread 1 " + a); }
}
}; Thread thread2 = new Thread() { public void run() { synchronized ("") { a = "maple"; try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} System.out.println("in thread 2 " + a);
} }
}; thread1.start(); thread2.start(); }}