学无先后,达者为师

网站首页 编程语言 正文

线程同步的使用--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

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新