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

  • 相关阅读:
    转发和重定向的区别
    关于Daydream VR的最直白的介绍
    Duplicate Protocol Definition of DTService Is Ignored
    automatically select architectures
    java
    初识反射
    java网络编程
    Map接口
    Set,List
    正则表达式
  • 原文地址:https://www.cnblogs.com/oushiyang/p/8479441.html
Copyright © 2011-2022 走看看