您的位置:首页 > 编程语言 > Java开发

多线程死锁的一个简单例子

2017-06-11 17:13 330 查看
package web1;

import java.util.concurrent.atomic.AtomicInteger;

public class Main1 {

    public static void main(String[] args) {
        AtomicInteger count = new AtomicInteger(0);
        int runCount = 3;
        ThreadTest3 t1 = new ThreadTest3(count, "A",0,runCount);
        ThreadTest3 t2 = new ThreadTest3(count, "B",1,runCount);
        ThreadTest3 t3 = new ThreadTest3(count, "C",2,runCount);
        t1.start();
        t2.start();
        t3.start();
    }
}
线程类代码:

package web1;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadTest3 extends Thread {
private AtomicInteger count ;
private String word=null;
private int order;
private int runCount;
public ThreadTest3(AtomicInteger count,String word,int order,int runCount){
this.count=count;
this.word=word;
this.order=order;
this.runCount=runCount;
}

@Override
public void run() {
while (true) {
synchronized (count) {
System.out.println("线程编号"+order+"取得对象锁");
if (count.get()%runCount==order) {
System.out.println(word+","+count.get());
count.getAndAdd(1);
count.notify();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
count.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
}
}

运行结果如下:

线程编号0取得对象锁

A,0

线程编号0取得对象锁

线程编号1取得对象锁

B,1

线程编号1取得对象锁

线程编号2取得对象锁

C,2

线程编号2取得对象锁

线程编号1取得对象锁

线程编号0取得对象锁

A,3

线程编号0取得对象锁

线程编号2取得对象锁

分析:

上面是运行结果的全部,即产生了死锁不再产生新的输出,下面我们按运行输出的每个步骤分析死锁是如何产生的:

输出1:线程编号0取得对象锁;

输出2:线程编号0打印字母A,然后唤醒一个正在等待的线程,此时各个线程状态:线程0--运行状态,线程1-运行状态,线程2-运行状态;

输出3:线程编号0再次取得对象锁,不符合条件进入等待状态,此时各个线程状态:线程0--等待状态,线程1-运行状态,线程2-运行状态;

输出4:线程编号1取得对象锁;

输出5:线程编号1打印字母B,然后唤醒一个正在等待的线程,只有线程0处于等待状态所以线程0被唤醒,此时各个线程状态:线程0--运行状态,线程1-运行状态,线程2-运行状态;

输出6:线程编号1再次取得对象锁,由于不符合打印条件进入等待状态,此时各个线程状态:线程0--运行状态,线程1-等待状态,线程2-运行状态;

输出7:线程编号2取得对象锁;

输出8:线程编号2打印字母C,然后唤醒一个正在等待的线程,只有线程1处于等待状态所以线程1被唤醒,此时各个线程状态:线程0--运行状态,线程1-运行状态,线程2-运行状态;

输出9:线程编号2再次取得对象锁,由于不符合打印条件进入等待状态,此时各个线程状态:线程0--运行状态,线程1-运行状态,线程2--等待状态;

输出10:线程编号1再次取得对象锁,由于不符合打印条件进入等待状态,此时各个线程状态:线程0--运行状态,线程1-等待状态,线程2-等待状态;

输出11:线程编号0取得对象锁;

输出12:线程编号0打印字母A,然后唤醒一个正在等待的线程,此时各个线程状态:线程0--运行状态,线程1-等待状态,线程2-运行状态;

输出13:线程编号0再次取得对象锁,不符合条件进入等待状态,此时各个线程状态:线程0--等待状态,线程1-等待状态,线程2-运行状态;

输出14:线程编号2取得对象锁,不符合条件进入等待状态,此时各个线程状态:线程0--等待状态,线程1-等待状态,线程2-等待状态;

至此所有线程都进入等待状态,程序不再继续执行。解决办法是将count.notify()修改为count.notifyAll()唤醒count对象的所有进程来竞争对象锁。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息