一、synchronized的缺陷测试代码
package communication;
import java.util.concurrent.TimeUnit;
public class SynchronizedDefect {
public synchronized void syncMethod(){
try {
System.out.println(Thread.currentThread().getName()+" start.");
TimeUnit.HOURS.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
}
public static void main(String []args) throws InterruptedException {
SynchronizedDefect defect=new SynchronizedDefect();
Thread t1=new Thread(defect::syncMethod,"T1");
t1.start();
TimeUnit.MILLISECONDS.sleep(2);
Thread t2=new Thread(defect::syncMethod,"T2");
t2.start();
t2.interrupt();
System.out.println("T2 interrupt:"+t2.isInterrupted());
System.out.println("T2 status:"+t2.getState());
}
}
二、运行结果