一直听说线程sleep不让出锁,现做个实验,代码如下
先写一个类,方法上都同步。
package test.thread.impl;
public class ThreadSleep {
public synchronized void method1() throws InterruptedException {
System.out.println("this is method1");
Thread.sleep(2000);
}
public synchronized void method2() throws InterruptedException {
System.out.println("this is method2");
Thread.sleep(3000);
}
}
再写两个测试的方法。
package test.thread.impl;
public class ThreadSleepTask1 implements Runnable {
public ThreadSleepTask1(ThreadSleep threadSleep) {
this.threadSleep = threadSleep;
}
private ThreadSleep threadSleep;
@Override
public void run() {
System.out.println("this is ThreadSleepTask1 invoke threadSleep method1");
try {
threadSleep.method1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package test.thread.impl;
public class ThreadSleepTask2 implements Runnable {
public ThreadSleepTask2(ThreadSleep threadSleep) {
this.threadSleep = threadSleep;
}
private ThreadSleep threadSleep;
@Override
public void run() {
System.out.println("this is ThreadSleepTask2 invoke threadSleep method2");
try {
threadSleep.method2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
再写一个测试类
package test.thread.impl;
public class ThreadSleepLock {
public static void main(String[] args) throws InterruptedException {
long beginTime = System.currentTimeMillis();
ThreadSleep threadSleep = new ThreadSleep();
ThreadSleepTask1 threadSleepTask1 = new ThreadSleepTask1(threadSleep);
ThreadSleepTask2 threadSleepTask2 = new ThreadSleepTask2(threadSleep);
Thread thread1 = new Thread(threadSleepTask1);
Thread thread2 = new Thread(threadSleepTask2);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
long endTime = System.currentTimeMillis();
System.out.println(endTime - beginTime);
}
}
运行结果如下:
可以看出,当方法上都加同步时候,这是在对象上加锁,当两个线程使用同一个对象时,方法顺序执行,看来sleep方法并没有让出锁。
当把其中一个同步方法拿掉时,运行时间就会缩短,由此看到,sleep时候并不会让出锁,不加锁的方法会正常运行
萌新才写博客,如有错误,还请大家多多指出,谢谢