java基础知识回顾之java Thread类学习(七)--java多线程安全问题(死锁)

死锁:是两个或者两个以上的线程被无限的阻塞,线程之间互相等待所需资源。

线程死锁产生的条件:

  • 当两个线程相互调用Join()方法。
  • 当两个线程使用嵌套的同步代码块的时候,一个线程占用了另一个线程的锁,互相等待阻塞,就有可能产生死锁。

下面看代码:

代码1:死锁的案例

package com.lp.ecjtu.Thread;

/*
死锁:常见情景之一:同步的嵌套。 */
class Ticket implements Runnable
{
private int num = 100;
Object obj = new Object();
boolean flag = true;
public void run()
{
if(flag)
while(true)
{
synchronized(obj)//同步代码块里面调用同步函数
{
show();
}
}
else
while(true)
this.show();
} public synchronized void show()//同步函数里面的调用同步代码块
{ synchronized(obj)
{
if(num>0)
{
try{Thread.sleep(10);}catch (InterruptedException e){} System.out.println(Thread.currentThread().getName()+".....sale...."+num--);
}
}
}
} public class DeathLockThread1
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try{Thread.sleep(10);}catch(InterruptedException e){}
t.flag = false;
t2.start();
}
}

代码2:

package com.lp.ecjtu.Thread;

 class DeathLockRunable implements Runnable{
private boolean flag;
public DeathLockRunable(boolean flag){
this.flag = flag;
} @Override
public void run() {
if(flag){
synchronized (Lock.mylock1){
System.out.println("if mylock1"+Thread.currentThread().getName());
synchronized (Lock.mylock2){
System.out.println("if mylock2"+Thread.currentThread().getName());
}
}
}else{
synchronized (Lock.mylock2){
System.out.println("else mylock2"+Thread.currentThread().getName());
synchronized (Lock.mylock1){
System.out.println("else mylock1"+Thread.currentThread().getName());
}
}
}
} } class Lock{
static Object mylock1 = new Object();
static Object mylock2 = new Object();
} public class DeathLockThread{
public static void main(String[] args){
Thread t1 = new Thread(new DeathLockRunable(true));
Thread t2 = new Thread(new DeathLockRunable(false));
t1.start();
t2.start();
}
}

输出结果:if mylock1Thread-0
else mylock2Thread-1

 
上一篇:《python基础教程(第二版)》学习笔记 字符串(第3章)


下一篇:vue Bus总线