死锁的应用

作者在 2010-05-23 20:06:25 发布以下内容
public class TestDeadLock{
    public static void main(String args[]){
        StringBuffer sb = new StringBuffer("ABCD");
        MyThread t = new MyThread(sb);
        t.start();    
        synchronized(sb){
            try{
                t.join();
            }catch(InterruptedException e){
                e.printStackTrace();    
            }
            System.out.println(sb);    
        }
        System.out.println("Main thread is over!");    
    }    
}

class MyThread extends Thread{
    private StringBuffer sb;
    public MyThread(StringBuffer sb){
        this.sb = sb;
    }
    public void run(){
        synchronized(sb){
            sb.reverse();
        }
        System.out.println("Sub thread is over!");    
    }    
}
public class TestDeadLock2{
    public static void main(String args[]){
        char[] a = {'A','B','C'};
        char[] b = {'D','E','F'};
        MyThread t1 = new MyThread(a,b);
        MyThread t2 = new MyThread(b,a);
        t1.start();
        t2.start();        
    }    
}

class MyThread extends Thread{
    private char[] source;
    private char[] dest;
    
    public MyThread(char[] source,char[] dest){
        this.source = source;
        this.dest = dest;
    }
    public void run(){
        synchronized(source){
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();    
            }
            
            synchronized(dest){
                System.arraycopy(source,0,dest,0,source.length);
                System.out.println(dest);
            }        
        }
    }    
}
线程 | 阅读 1021 次
文章评论,共0条
游客请输入验证码
浏览290848次