package com;
public class TestThread009 {
static Object a = new Object();
static Object b = new Object();
public static void main(String[] args) {
new Thread(()->{
synchronized (a){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (b){
System.out.println(1);
}
}
}).start();
new Thread(()->{
synchronized (b){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (a){
System.out.println(1);
}
}
}).start();
}
}
可重入锁的练习:
package com;
import java.util.concurrent.locks.ReentrantLock;
public class TestThread010 {
public static void main(String[] args) {
LockTest test = new LockTest();
Thread thread1 = new Thread(test);
Thread thread2 = new Thread(test);
thread1.start();
thread2.start();
}
}
class LockTest implements Runnable{
private int count = 10;
ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (count>0){
try {
lock.lock();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(count--);
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
}