zoukankan      html  css  js  c++  java
  • java同步锁synchronized的使用

    synchronized 同步锁 ,首先需要明白同步和异步的关系,所谓同步,就是事情需要一步一步的做,反之为异步,异步就是在做这件事的时候也可以做其他的事情。

    这是上了锁之后的情况

    public class Threadddddddddddd implements Runnable{

    @Override
    public synchronized void run() {
    for(int i =0;i<5;i++){
    try {
    Thread.sleep(2000);
    } catch (Exception e) {
    e.printStackTrace();
    }
    System.out.println(Thread.currentThread().getName()+"------"+i);
    }
    }
    public static void main(String[] args) {
    Threadddddddddddd threadddddddddddd = new Threadddddddddddd();
    Thread thread = new Thread(threadddddddddddd, "a");
    thread.start();
    Thread thread1 = new Thread(threadddddddddddd, "b");
    thread1.start();
    }
    }

    输出结果

    a------0
    a------1
    a------2
    a------3
    a------4
    b------0
    b------1
    b------2
    b------3
    b------4

    未上锁

    public class Threadddddddddddd implements Runnable{

    @Override
    public void run() {
    for(int i =0;i<5;i++){
    try {
    Thread.sleep(2000);
    } catch (Exception e) {
    e.printStackTrace();
    }
    System.out.println(Thread.currentThread().getName()+"------"+i);
    }
    }
    public static void main(String[] args) {
    Threadddddddddddd threadddddddddddd = new Threadddddddddddd();
    Thread thread = new Thread(threadddddddddddd, "a");
    thread.start();
    Thread thread1 = new Thread(threadddddddddddd, "b");
    thread1.start();
    }
    }

    输出结果:

    a------0
    b------0
    a------1
    b------1
    a------2
    b------2
    a------3
    b------3
    a------4
    b------4

  • 相关阅读:
    设计模式 -- 桥接模式(Bridge)
    设计模式 -- 单例模式(Singleton)
    设计模式 -- 简单工厂模式
    Nginx服务器的启动控制
    【Vue.js】二、Vue的基础
    【Vue.js】一、Vue介绍和安装使用
    linux常用操作命令
    Redis的学习(一、Redis的一些常用技术)
    Spring的学习(四、Spring事务管理)
    Spring的学习(三、Spring中的AOP)
  • 原文地址:https://www.cnblogs.com/oushiyang/p/8479441.html
Copyright © 2011-2022 走看看