public class TestDeadLock implements Runnable {
public int flag = 1;
static Object o1 = new Object(), o2 = new Object();
public void run() {
System.out.println("flag=" + flag);
if(flag == 1) {
synchronized(o1) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized(o2) {
System.out.println("1");
}
}
}
if(flag == 0) {
synchronized(o2) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized(o1) {
System.out.println("0");
}
}
}
}
public static void main(String[] args) {
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
t2.start();
}
}
如上述代码 死锁
td1 和 td2为不同的对象`
他们分属于不同的线程为何td1执行完synchronized(o1)的代码后
需要对象td2 对o2的锁
他们既然是不同的对象`
就应该互不干涉啊`
为什么还会发生死锁的现象呢`本人初学java
勿见笑。
public int flag = 1;
static Object o1 = new Object(), o2 = new Object();
public void run() {
System.out.println("flag=" + flag);
if(flag == 1) {
synchronized(o1) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized(o2) {
System.out.println("1");
}
}
}
if(flag == 0) {
synchronized(o2) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized(o1) {
System.out.println("0");
}
}
}
}
public static void main(String[] args) {
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
t2.start();
}
}
如上述代码 死锁
td1 和 td2为不同的对象`
他们分属于不同的线程为何td1执行完synchronized(o1)的代码后
需要对象td2 对o2的锁
他们既然是不同的对象`
就应该互不干涉啊`
为什么还会发生死锁的现象呢`本人初学java
勿见笑。
o1与o2都表示当前对象。
也就是说,因为synchronized(o1)把当前对象锁了,但是synchronized(o2)又要锁,所以就死锁了。
public class DeadLockTest implements Runnable{
protected Resource resA, resB; public DeadLockTest(Resource r1, Resource r2) {
resA=r1;
resB=r2;
} public void run() { // called by t thread
write(38,36); //call write()
}
public void write(int num1, int num2) { // called by run method of t thread
synchronized(resA){
try {
System.out.println(" write thread");
Thread.sleep(10);
}catch(Exception e){
e.printStackTrace();
}
synchronized(resB){
resA.number=num1;
resB.number=num2;
System.out.println(" Resource A, number is: " + resA.number);
System.out.println(" Resource B, number is: " +resB.number );
}
}
} public int read() { // called by main thread
synchronized(resB){
try {
System.out.println(" read thread");
Thread.sleep(10);
}catch(Exception e){
e.printStackTrace();
} synchronized(resA){
int totalNum=resA.number+resB.number;
System.out.println(" Resource A and B, total number " + totalNum);
return totalNum;
}
}
} public static void main(String[] args) {
DeadLockTest q=new DeadLockTest(new Resource(20), new Resource(30));
Thread t=new Thread(q);
t.start(); //start t Thread, call run method
q.read(); // called by main thread
}
}class Resource{
int number;
public Resource(int num){
number=num;
}
}