面试点
线程在执行yield()以后,线程持有的锁是不释放的
线程在执行sleep()方法被调用以后,线程持有的锁是不释放的
线程在调用wait()和notify()方法之前,必须要先持有锁。调用了wait()方法以后,锁就会被释放,当wait方法返回的时候,线程会重新持有锁
调动notify(),notifyAll()方法之前,必须要先持有锁,调用notify(),notifyAll()方法本身不会释放锁的,等到 同步方法或同步块执行完以后,才会释放锁。
public class SleepLock {
private Object lock = new Object();
public static void main(String[] args) {
SleepLock sleepTest = new SleepLock();
Thread threadA = sleepTest.new ThreadSleep();
threadA.setName("ThreadSleep");
Thread threadB = sleepTest.new ThreadNotSleep();
threadB.setName("ThreadNotSleep");
threadA.start();
try {
Thread.sleep(1000);
System.out.println(" Main slept!");
} catch (InterruptedException e) {
e.printStackTrace();
}
threadB.start();
}
private class ThreadSleep extends Thread {
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " will take the lock");
try {
synchronized (lock) {
System.out.println(threadName + " taking the lock");
System.out.println("Finish the work: " + threadName);
}
Thread.sleep(5000);
} catch (InterruptedException e) {
//e.printStackTrace();
}
}
}
private class ThreadNotSleep extends Thread {
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " will take the lock time=" + System.currentTimeMillis());
synchronized (lock) {
System.out.println(threadName + " taking the lock time=" + System.currentTimeMillis());
System.out.println("Finish the work: " + threadName);
}
}
}
}