我的java多线程死锁例子为什么没写对?
代码是这样的没实现死锁publicclassDeathLockTest{publicstaticvoidmain(String[]args){//TODOAuto-gen...
代码是这样的 没实现死锁
public class DeathLockTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
DeathRunnable r=new DeathRunnable();
Thread t1=new Thread(r,"t1");
Thread t2=new Thread(r,"t2");
t1.start();
t2.start();
}
}
class DeathRunnable implements Runnable{
Object obj1=new Object();
Object obj2=new Object();
@Override
public void run() {
// TODO Auto-generated method stub
if(Thread.currentThread().getName().equals("t1")){
synchronized(obj2){
System.out.println("线程1锁定obj1");
}
synchronized(obj1){
System.out.println("线程1锁定obj2");
}
}else if(Thread.currentThread().getName().equals("t2")){
synchronized(obj1){
System.out.println("线程2锁定obj2");
}
synchronized(obj2){
System.out.println("线程2锁定obj1");
}
}
}
} 展开
public class DeathLockTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
DeathRunnable r=new DeathRunnable();
Thread t1=new Thread(r,"t1");
Thread t2=new Thread(r,"t2");
t1.start();
t2.start();
}
}
class DeathRunnable implements Runnable{
Object obj1=new Object();
Object obj2=new Object();
@Override
public void run() {
// TODO Auto-generated method stub
if(Thread.currentThread().getName().equals("t1")){
synchronized(obj2){
System.out.println("线程1锁定obj1");
}
synchronized(obj1){
System.out.println("线程1锁定obj2");
}
}else if(Thread.currentThread().getName().equals("t2")){
synchronized(obj1){
System.out.println("线程2锁定obj2");
}
synchronized(obj2){
System.out.println("线程2锁定obj1");
}
}
}
} 展开
3个回答
展开全部
死锁的前提是。两个人吃饭,都需要需要刀和叉但又只有一套, 其中一个人拿了叉,另一个拿了刀,就出现互相等待的情况。你的obj1和obj2就相当于刀叉,但是你并没有说拿了叉,还会继续去拿刀。你的代码意思是,t1拿叉,然后放下叉,然后去拿刀。t2做的动作是拿刀,放下刀,再拿叉。他们之间的动作并不会导致矛盾。我给你改成下面这样了,但是这样也不一定会导致死锁,因为你没有做循环,只做一次操作,万一t1跑的快,瞬间就做完所有操作了,也不会阻塞t2.
if(Thread.currentThread().getName().equals("t1")){
synchronized(obj2){
System.out.println("线程1锁定obj2");
synchronized(obj1){
System.out.println("线程1锁定obj1");
}
}
}else if(Thread.currentThread().getName().equals("t2")){
synchronized(obj1){
System.out.println("线程2锁定obj1");
synchronized(obj2){
System.out.println("线程2锁定obj2");
}
}
}
if(Thread.currentThread().getName().equals("t1")){
synchronized(obj2){
System.out.println("线程1锁定obj2");
synchronized(obj1){
System.out.println("线程1锁定obj1");
}
}
}else if(Thread.currentThread().getName().equals("t2")){
synchronized(obj1){
System.out.println("线程2锁定obj1");
synchronized(obj2){
System.out.println("线程2锁定obj2");
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询