java多线程学习笔记3

/**
 * 一个产生deadlock的例子
 * 
@author midi
 *
 
*/

public class Deadlock extends Object {
    
private String objID;

    
public Deadlock(String id) {
        objID 
= id;
    }


    
public synchronized void checkOther(Deadlock other) {
        print(
"entering checkOther()");

        
// simulate some lengthy process
        try {
            Thread.sleep(
2000);
        }
 catch (InterruptedException x) {
        }


        print(
"in checkOther() - about to " + "invoke 'other.action()'");
        other.action();

        print(
"leaving checkOther()");
    }


    
public synchronized void action() {
        print(
"entering action()");

        
// simulate some work here
        try {
            Thread.sleep(
500);
        }
 catch (InterruptedException x) {
        }


        print(
"leaving action()");
    }


    
public void print(String msg) {
        threadPrint(
"objID=" + objID + " - " + msg);
    }


    
public static void threadPrint(String msg) {
        String threadName 
= Thread.currentThread().getName();
        System.out.println(threadName 
+ "" + msg);
    }


    
public static void main(String[] args) {
        
final Deadlock obj1 = new Deadlock("obj1");
        
final Deadlock obj2 = new Deadlock("obj2");

        Runnable runA 
= new Runnable() {
            
public void run() {
                obj1.checkOther(obj2);
            }

        }
;

        Thread threadA 
= new Thread(runA, "threadA");
        threadA.start();

        
try {
            Thread.sleep(
200);
        }
 catch (InterruptedException x) {
        }


        Runnable runB 
= new Runnable() {
            
public void run() {
                obj2.checkOther(obj1);
            }

        }
;

        Thread threadB 
= new Thread(runB, "threadB");
        threadB.start();

        
try {
            Thread.sleep(
5000);
        }
 catch (InterruptedException x) {
        }


        threadPrint(
"finished sleeping");

        threadPrint(
"about to interrupt() threadA");
        threadA.interrupt();

        
try {
            Thread.sleep(
1000);
        }
 catch (InterruptedException x) {
        }


        threadPrint(
"about to interrupt() threadB");
        threadB.interrupt();

        
try {
            Thread.sleep(
1000);
        }
 catch (InterruptedException x) {
        }


        threadPrint(
"did that break the deadlock?");
    }

}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值