import java.util.concurrent.*;
import java.util.*;

public class Deadlock {
    public static void main(String[] args)
    {
        ExecutorService executor = Executors.newCachedThreadPool();
        executor.execute(new R());
        executor.execute(new W());        
        executor.shutdown();
    }

    private static Semaphore mutex1 = new Semaphore(1);
    private static Semaphore mutex2 = new Semaphore(1);


    private static class R implements Runnable 
    {
        public void run()
        {
            try
            {
                while ( true )
                {
                    mutex1.acquire();
                    System.out.println("Get 1");
                    Thread.sleep((int)(Math.random() * 1000));
                    
                    mutex2.acquire();
                    System.out.println("Get 2");
                    Thread.sleep((int)(Math.random() * 1000));

                    
                    mutex2.release();
                    mutex1.release();
                    
                    Thread.sleep((int)(Math.random() * 1000));
                }
            }

            catch( InterruptedException ex )
            {
                ex.printStackTrace();
            }
        }
    }

    private static class W implements Runnable 
    {
        public void run()
        {
            try 
            {
                while ( true )
                {
                    mutex2.acquire();
                    System.out.println("\t\t\tGet 2");
                    Thread.sleep((int)(Math.random() * 1000));
                    
                    mutex1.acquire();
                    System.out.println("\t\t\tGet 1");
                    Thread.sleep((int)(Math.random() * 1000));

                    mutex1.release();
                    mutex2.release();
                    
                    Thread.sleep((int)(Math.random() * 1000));
                }
            }

            catch( InterruptedException ex )
            {
                ex.printStackTrace();
            }
        }
    }
}

 

posted on 2013-04-20 20:10  Sinker  阅读(153)  评论(0编辑  收藏  举报