一个程序就是一个进程
多线程指在同一个程序中的多个应用和功能
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---独家制作
版权所有,盗版必究!
网友评论