- public class Sisuo implements Runnable {
- Object obj1 = new Object();
- Object obj2 = new Object();
- @Override
- public void run() {
- if (Thread.currentThread().getName().equals("t1")) {
- while (true) {
- synchronized (obj1) {
- System.out.println("线程t1锁定obj1");
- synchronized (obj2) {
- System.out.println("线程t1锁定obj2");
- }
- }
- }
- } else {
- while (true) {
- synchronized (obj2) {
- System.out.println("线程t2锁定obj2");
- synchronized (obj1) {
- System.out.println("线程t2锁定obj1");
- }
- }
- }
- }
- }
- public static void main(String[] args) {
- Sisuo sisuo=new Sisuo();
- Thread t1 = new Thread(sisuo, "t1");
- Thread t2 = new Thread(sisuo, "t2");
- t1.start();
- t2.start();
- }
- }
复制代码 |