线程死锁:
创建两个字符串a和b,再创建两个线程A和B,让每个线程都用synchronized锁住字符串(A先锁a,再去锁b;B先锁b,再锁a),如果A锁住a,B锁住b,A就没办法锁住b,B也没办法锁住a,这时就陷入了死锁。直接贴代码:
/*
线程死锁
*/
public class DeadLock {
public static String str1 = "str1";
public static String str2 = "str2";
public static void main(String[] args) {
Thread t1 = new Thread(new Lock1());
Thread t2 = new Thread(new Lock2());
t1.start();
t2.start();
}
}
class Lock1 implements Runnable{
@Override
public void run() {
try {
System.out.println("线程"+Thread.currentThread().getName()+"开始运行");
while (true){
synchronized (DeadLock.str1){
System.out.println("线程"+Thread.currentThread().getName()+"锁住str1");
Thread.sleep(3000);
synchronized (DeadLock.str2){
System.out.println("线程"+Thread.currentThread().getName()+"锁住str2");
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
class Lock2 implements Runnable{
@Override
public void run() {
try {
System.out.println("线程"+Thread.currentThread().getName()+"开始运行");
while (true){
synchronized (DeadLock.str2){
System.out.println("线程"+Thread.currentThread().getName()+"锁住str2");
Thread.sleep(3000);
synchronized (DeadLock.str1){
System.out.println("线程"+Thread.currentThread().getName()+"锁住str1");
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}