日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

線程同步的使用--this作為線程對象鎖synchronized關鍵字

作者:Qiddo 更新時間: 2023-12-12 編程語言

synchronized關鍵字的語法結構

synchronized(this){ 
    //同步代碼 
}

或者在方法上添加了synchronized的,如下

public synchronized void accessVal(int newVal){

    //同步代碼

}

實例:(可以拿去Idea上復制粘貼運行一下)

/**
 * 定義程序員類
 */
class Programmer{
  private String name;
  public Programmer(String name){
    this.name = name;
   }
  /**
   * 打開電腦
   */
  synchronized public void computer(){
      try {
        System.out.println(this.name + " 接通電源");
        Thread.sleep(500);
        System.out.println(this.name + " 按開機按鍵");
        Thread.sleep(500);
        System.out.println(this.name + " 系統啟動中");
        Thread.sleep(500);
        System.out.println(this.name + " 系統啟動成功");
       } catch (InterruptedException e) {
        e.printStackTrace();
       }
   }
  /**
   * 編碼
   */
  synchronized public void coding(){
      try {
        System.out.println(this.name + " 雙擊Idea");
        Thread.sleep(500);
        System.out.println(this.name + " Idea啟動完畢");
        Thread.sleep(500);
        System.out.println(this.name + " 開開心心的寫代碼");
       } catch (InterruptedException e) {
        e.printStackTrace();
       }
     }
}


/**
 * 打開電腦的工作線程
 */
class Working1 extends Thread{
  private Programmer p;
  public Working1(Programmer p){
    this.p = p;
   }
  @Override
  public void run() {
    this.p.computer();
   }
}


/**
 * 編寫代碼的工作線程
 */
class Working2 extends Thread{
  private Programmer p;
  public Working2(Programmer p){
    this.p = p;
   }
  @Override
  public void run() {
    this.p.coding();
   }
}
public class TestSyncThread {
  public static void main(String[] args) {
    Programmer p = new Programmer("張三");
    new Working1(p).start();
    new Working2(p).start();
   }
}

原文鏈接:https://blog.csdn.net/m0_73944607/article/details/130669381

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新