java 线程,怎么写个死锁的程序
publicclassdeadLockimplementsRunnable{publicintflag=1;staticObjecto1=newObject(),o2=n...
public class deadLock 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(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (o2) {
System.out.println("1");
}
}
if (flag == 0) {
synchronized (o2) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (o1) {
System.out.println("0");
}
}
}
public static void main(String[] args) {
deadLock r1 = new deadLock();
deadLock r2 = new deadLock();
r1.flag = 1;
r2.flag = 0;
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
我想制造个死锁,可为什么我的程序尽然没有死锁,是不是因为我的机器是双核的原因,?? 展开
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(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (o2) {
System.out.println("1");
}
}
if (flag == 0) {
synchronized (o2) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (o1) {
System.out.println("0");
}
}
}
public static void main(String[] args) {
deadLock r1 = new deadLock();
deadLock r2 = new deadLock();
r1.flag = 1;
r2.flag = 0;
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
我想制造个死锁,可为什么我的程序尽然没有死锁,是不是因为我的机器是双核的原因,?? 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询