synchronzied同步程式碼塊的使用——T2202
阿新 • • 發佈:2021-01-11
package 物件及變數的併發訪問2;
/**
* synchronzied同步程式碼塊的使用
*
* 當兩個併發執行緒訪問同一個物件object中的synchronized(this)同步程式碼塊時,一段時間內只能有一個執行緒得到執行,
*另一個執行緒必須等待當前執行緒執行完這個程式碼塊以後才能執行這個程式碼塊。
*
* 結果:雖然使用了synchronized同步程式碼塊,但執行的效率還是沒有提高,仍然是同步執行的。
*
*/
class ObjectServiceT2220{
public void serviceMethod () {
try {
synchronized (this){
System.out.println("begin time="+System.currentTimeMillis());
Thread.sleep(2000);
System.out.println("end end="+System.currentTimeMillis());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyThreadAT2220 extends Thread{
private ObjectServiceT2220 objectServiceT2220;
public MyThreadAT2220(ObjectServiceT2220 objectServiceT2220){
super();
this.objectServiceT2220=objectServiceT2220;
}
@Override
public void run() {
super.run();
objectServiceT2220.serviceMethod();
}
}
class MyThreadBT2220 extends Thread{
private ObjectServiceT2220 objectServiceT2220;
public MyThreadBT2220(ObjectServiceT2220 objectServiceT2220){
super();
this.objectServiceT2220=objectServiceT2220;
}
@Override
public void run() {
super.run();
objectServiceT2220.serviceMethod();
}
}
class RunT2202{
public RunT2202(){
ObjectServiceT2220 objectServiceT2220=new ObjectServiceT2220();
MyThreadAT2220 at2220=new MyThreadAT2220(objectServiceT2220);
at2220.setName("A");
at2220.start();
MyThreadBT2220 bt2220=new MyThreadBT2220(objectServiceT2220);
bt2220.setName("B");
bt2220.start();
}
}
public class T2202 {
public static void main(String[] args) {
RunT2220 runT2220=new RunT2220();
}
}