产生背景
不同线程分别占用对方需要的同步资源部放弃,都在等待对方放弃自己需要的同步资源,形成了线程的死锁
解决方法
专门的算法,原则
尽量减少同步资源的定义
案例
package com.zyd.thread;
public class TestDeadLock {
static StringBuilder sb1 = new StringBuilder();
static StringBuilder sb2 = new StringBuilder();
public static void main (String[] args){
new Thread(){
public void run(){
synchronized (sb1){
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
sb1.append("A");
synchronized (sb2){
sb2.append("B");
System.out.println(sb1);
System.out.println(sb2);
}
}
}
}.start();
new Thread(){
public void run(){
synchronized (sb2){
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
sb1.append("C");
synchronized (sb1){
sb2.append("D");
System.out.println(sb1);
System.out.println(sb2);
}
}
}
};
}
}
线程的通信
定义在Object里面
wait():令当前线程挂起并放弃CPU,同步资源,使别的线程可访问并修改共享资源,而当前线程排队等待再次对资源的访问
notify():唤醒正在排队等待同步资源的线程中优先级最高者结束等待
notifyAll():唤醒正在排队等待资源的所有线程结束等待
注意:
这桑方法只有在synchronized方法或synchronized代码块中才能使用,否则报错
java.lang.IllegalMonitorStateException异常
案例:使用两个线程打印 1-100. 线程1, 线程2 交替打印
package com.zyd.thread;
class PrintNum implements Runnable {
int num = 1;
Object obj = new Object();
@Override
public void run() {
while (true){
synchronized (obj){
obj.notify();
if (num <= 100){
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":"+num);
num++;
}else {
break;
}
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class TestCommunication{
public static void main (String[] args){
PrintNum p = new PrintNum();
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
t1.setName("A:");
t2.setName("B");
t1.start();
t2.start();
}
}