练习代码

Posted zhongchang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了练习代码相关的知识,希望对你有一定的参考价值。

1.DeadThread 死锁

public class DeadThread 

    private static Object monitorA = new Object();

    private static Object monitorB = new Object();

    public static void main(String[] args) 
        Thread threadA = new Thread(new Runnable() 
            @Override
            public void run()   
                synchronized(monitorA) 
                    System.out.println("线程A获取已获取锁A");
                    try 
                        Thread.sleep(100);
                     catch (InterruptedException e) 
                        e.printStackTrace();
                    

                    System.out.println("线程A准备获取锁B");
                    synchronized(monitorB) 
                        System.out.println("线程A已经获取锁B");
                    
                
                System.out.println("线程A run方法结束");
            
        );

        Thread threadB = new Thread(new Runnable() 
            @Override
            public void run()   
                synchronized(monitorB) 
                    System.out.println("线程B获取已获取锁B");
                    try 
                        Thread.sleep(100);
                     catch (InterruptedException e) 
                        e.printStackTrace();
                    

                    System.out.println("线程B准备获取锁A");
                    synchronized(monitorA) 
                        System.out.println("线程B已经获取锁A");
                    
                
                System.out.println("线程B run方法结束");
            
        );

        threadA.start();
        threadB.start();
    

2.排序 2分排序

以上是关于练习代码的主要内容,如果未能解决你的问题,请参考以下文章