public class Service {
public void testSleep() {
synchronized (this) {
this.notify();
try {
System.out.println("sleep测试开始");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sleep测试");
}
}
public void testWait() {
synchronized (this) {
try {
System.out.println("wait等待开始");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("wait测试");
}
}
public static void main(String[] args) throws InterruptedException {
//只初始化一个对象,保证锁是同一把
Service service = new Service();
Thread t1 = new Thread(new T1(service));
Thread t2 = new Thread(new T2(service));
t2.start();
t1.start();
}
}
class T1 implements Runnable {
private Service service;
public T1(Service service){
this.service = service;
}
@Override
public void run() {
service.testSleep();
}
}
class T2 implements Runnable{
private Service service;
public T2(Service service){
this.service = service;
}
@Override
public void run() {
service.testWait();
}
}
输出结果
从上面输出结果的展示,很明显的看出来wait会释放锁,sleep不会释放,再由下面这个进一步看wait方法锁的释放
public class Service {
public void testSleep() {
synchronized (this) {
this.notify();
try {
System.out.println("sleep测试开始");
Thread.sleep(1000);
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sleep测试");
}
}
public void testWait() {
synchronized (this) {
try {
System.out.println("wait等待开始");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
this.notify();
System.out.println("wait测试");
}
}
public static void main(String[] args) throws InterruptedException {
//只初始化一个对象,保证锁是同一把
Service service = new Service();
Thread t1 = new Thread(new T1(service));
Thread t2 = new Thread(new T2(service));
t2.start();
t1.start();
}
}
class T1 implements Runnable {
private Service service;
public T1(Service service){
this.service = service;
}
@Override
public void run() {
service.testSleep();
}
}
class T2 implements Runnable{
private Service service;
public T2(Service service){
this.service = service;
}
@Override
public void run() {
service.testWait();
}
}
输出结果