首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

这算不算一个java线程死锁多事例?

2013-02-17 
这算不算一个java线程死锁多例子??package com.zdyn.actionpublic class TestThread {public static int

这算不算一个java线程死锁多例子??

package com.zdyn.action;

public class TestThread {

public static int flag = 1;

public static void main(String[] args) {
Thread t1 = new Thread(new Demo1());
Thread t2 = new Thread(new Demo2());
t1.start();
t2.start();
}
}

class Demo1 implements Runnable {

public void run() {

while (true) {
if (TestThread.flag == 1) {

System.out.println(TestThread.flag = 2);

}
}
}

}

class Demo2 implements Runnable {

public void run() {

if (TestThread.flag == 2) {

System.out.println(TestThread.flag = 1);
}

}
}

[解决办法]
感觉不算 给LZ写了个死锁仅供LZ参考

class Test implements Runnable
{
private boolean flag;

public Test(boolean flag)
{
this.flag = flag;
}

public void run()
{

if(flag)
{
while(true)
{
synchronized(MyLock.locka)
{
System.out.println("if locka");
synchronized(MyLock.lockb)
{
System.out.println("if lockb");
}
}
}
}
else
{
while(true)
{
synchronized(MyLock.lockb)
{
System.out.println("else lockb");
synchronized(MyLock.locka)
{
System.out.println("else locka");
}
}
}
}
}
}

class MyLock
{
static Object locka = new Object();
static Object lockb = new Object();
}



class  DeadLockTest
{
public static void main(String[] args) 
{
Thread t1 = new Thread(new Test(true));
Thread t2 = new Thread(new Test(false));

t1.start();
t2.start();
}
}

[解决办法]
额你的代码和死锁完全没关系,一般同步的时候才会引起死锁,比如线程One完成一个任务需要A的锁,自己此时有B的锁拿着不放,而线程Two完成一个任务需要B的锁,而自己拿着A的锁不放。这时候当2个人都不肯释放对方需要的锁的时候就会生产死锁。。。。

热点排行
Bad Request.