public class lock {
public static void main(String agrs[]) {
object o=new object();
object i=new object();
new t1(o,i).start();
new t3(o,i).start();
while(true) {
try {
Thread.sleep(500);
}catch(Exception e) {
}
System.out.println("主线程运行中");
}
}
}
class object{
public boolean run() {
return true;
}
}
class t1 extends Thread{
object o;
object i;
public t1(object o,object i) {
this.o=o;
this.i=i;
}
@Override
public void run() {
synchronized(o) {
try {
sleep(100);}
catch(Exception e) {
e.printStackTrace();
}
System.out.println("进入死锁");
synchronized(i) {
while(i.run()) {
System.out.println("t1等待中");
}}
}
}
}
class t3 extends Thread{
object o;
object i;
public t3(object o,object i) {
this.o=o;
this.i=i;
}
@Override
public void run() {
synchronized(i) {
try {
sleep(100);}//给予一定时间让另一个线程获得o的锁。下同
catch(Exception e) {
}
System.out.println("进入死锁");
synchronized(o) {
while(o.run()) {
System.out.println("t2等待中");
}}
}
}
}
Java死锁自己写的一个例子
猜你喜欢
转载自blog.csdn.net/qq_41105058/article/details/81128954
今日推荐
周排行