/**
* Created with IntelliJ IDEA.
* Description: If you don't work hard, you will a loser.
* User: Listen-Y.
* Date: 2020-10-03
* Time: 21:17
*/publicclassMyService{private String lock ="123";publicvoidtestMethod(){synchronized(lock){
System.out.println(Thread.currentThread().getName()+" begin at: "+ System.currentTimeMillis());
lock ="456";try{
Thread.sleep(2000);}catch(InterruptedException e){
e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+" end at: "+ System.currentTimeMillis());}}}
執行緒類和啟動類
/**
* Created with IntelliJ IDEA.
* Description: If you don't work hard, you will a loser.
* User: Listen-Y.
* Date: 2020-10-03
* Time: 21:21
*/publicclassRun2{publicstaticvoidmain(String[] args)throws InterruptedException {
MyService service =newMyService();
Thread t1 =newThread("A"){@Overridepublicvoidrun(){
service.testMethod();}};
Thread t2 =newThread("B"){@Overridepublicvoidrun(){
service.testMethod();}};
t1.start();//關鍵點 這裡等待0.1秒, A執行緒等待2秒
Thread.sleep(100);
t2.start();}}
/**
* Created with IntelliJ IDEA.
* Description: If you don't work hard, you will a loser.
* User: Listen-Y.
* Date: 2020-10-03
* Time: 21:50
*/publicclassRun3{publicstaticvoidmain(String[] args)throws InterruptedException {
User user =newUser("listen",20);
Service service =newService();
Thread t1 =newThread("A"){@Overridepublicvoidrun(){
service.testMethod(user);}};
Thread t2 =newThread("B"){@Overridepublicvoidrun(){
service.testMethod(user);}};
t1.start();//關鍵點
Thread.sleep(100);
t2.start();}}