您的位置:首页 > 其它

死锁案例分析

2018-01-03 23:16 639 查看
死锁的产生以及解决办法,看代码分析,注意里边的注释,自行运行。

package thread;

/**
* 模拟买票
*
* @author yhl
*
*/

class Thread02 implements Runnable{
private static int countTraket = 100;
public boolean flag = true;
private  Object mutex  = new Object();
@Override
public void run() {
if (flag) {
while (true) {
synchronized (mutex) {
// 锁(同步代码块)在什么时候释放? 代码执行完, 自动释放锁.
// 如果flag为true 线程1 先拿到 obj锁,在拿到this 锁、 才能执行。
// 如果flag为false 线程2 先拿到this,在拿到obj锁,才能执行。
// 死锁的产生:同步中嵌套同步,互不释放。
// 死锁解决办法:不要在同步中嵌套同步。
sale();
}
}
} else {
while (true) {
sale();
}
}

}

//同步代码块
public void sale(){
synchronized(mutex){
if(countTraket>0){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("当前线程:"+Thread.currentThread().getName()+";正在买第"+(100-countTraket+1)+"张票。");
countTraket--;
}
}
}

//同步函数
public synchronized void sale1(){
if(countTraket>0){
System.out.println("当前线程:"+Thread.currentThread().getName()+";正在买第"+(100-countTraket+1)+"张票。");
countTraket--;
}
}
public static synchronized void sale2(){
if(countTraket>0){
System.out.println("当前线程:"+Thread.currentThread().getName()+";正在买第"+(100-countTraket+1)+"张票。");
countTraket--;
}
}

}
public class ThreadDemo1 {

public static void main(String[] args) throws InterruptedException {

Thread02 t  = new Thread02();
Thread t1 = new Thread(t,"窗口1");
Thread t2 = new Thread(t,"窗口2");
t1.start();
Thread.sleep(50);
t.flag=false;
t2.start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程 死锁