美文网首页
聪聪工作室---多线程--- LearnThreadDeadLo

聪聪工作室---多线程--- LearnThreadDeadLo

作者: 繁花流水congcong | 来源:发表于2016-08-04 20:27 被阅读28次

    一个程序就是一个进程

    多线程指在同一个程序中的多个应用和功能

    LearnThreadDeadLock.java 代码

    package SiLock;
    
    import java.util.concurrent.SynchronousQueue;
    
    public class LearnThreadDeadLock {
        public static void main(String[] args) {
            Object lock1 = new Object();
            Object lock2 = new Object();
    
            Thread ta = new ThreadA(lock1, lock2);
            Thread tb = new ThreadB(lock1, lock2);
            ta.start();
            tb.start();
        }
    
    }
    
    class ThreadA extends Thread {
        Object lock1;
        Object lock2;
    
        public ThreadA(Object lock1, Object lock2) {
            this.lock1 = lock1;
            this.lock2 = lock2;
        }
    
        @Override
        public void run() {
            synchronized (lock1) {
                System.out.println("线程A拿到了Lock1");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
                synchronized (lock2) {
    
                    System.out.println("线程A拿到了Lock1和Lock2");
                }
            }
        }
    }
    
    class ThreadB extends Thread {
    
        Object lock1;
        Object lock2;
    
        public ThreadB(Object lock1, Object lock2) {
            this.lock1 = lock1;
            this.lock2 = lock2;
        }
    
        @Override
        public void run() {
            synchronized (lock1) {
    
                System.out.println("线程B拿到了Lock2");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
                synchronized (lock2) {
                    System.out.println("线程B拿到了lock1和lock2");
                }
            }
        }
    }
    
    
    lock.png

    作者: 聪聪工作室
    业务合作: 18758171751
    微信: 18758171751
    Email: 1099749430@qq.com

    聪聪工作室---Java---独家制作
    版权所有,盗版必究!

    相关文章

      网友评论

          本文标题:聪聪工作室---多线程--- LearnThreadDeadLo

          本文链接:https://www.haomeiwen.com/subject/fffhsttx.html