synchronized是Java中的关键字,是一种同步锁。它修饰的对象有以下几种:

  1. 修饰一个代码块,被修饰的代码块称为同步语句块,其作用的范围是大括号{}括起来的代码,作用的对象是调用这个代码块的对象; 
  2. 修饰一个方法,被修饰的方法称为同步方法,其作用的范围是整个方法,作用的对象是调用这个方法的对象; 
  3. 修改一个静态的方法,其作用的范围是整个静态方法,作用的对象是这个类的所有对象; 
  4. 修改一个类,其作用的范围是synchronized后面括号括起来的部分,作用主的对象是这个类的所有对象。

问题:

  class test1{

    public static synchronized void t11()

    public synchronized void t12()

    public synchronized void t13()

    public void t14()

  }

  这几个函数哪几个之间存在竞争关系?

Synchronized  :锁住的是对象,出现synchronized表示随后的代码块要用到共享数据了,要锁住了。

Synchronized  4种形式。

  1、synchronized(obj):可以任意指定对象.

  2、synchronized(this):当前对象:当一个类加到内存时,常量池有一个地址直接指向当前正在执行的对象.

  3、public synchronized void run():当前对象(this),这是实例方法,每一方法里存着一个This.方法

  对象:可以是普通类 public class Test {}, 也可以是干活线程类 ,只要是new 类名 的所有对象。

  4、public static synchronized void test () : 由类加载器加载的class字节码文件(XXX.class、this.getClass)

到这里上面的问题就知道答案:t12与t13 之间存在竞争关系

下面我们开始验证public static synchronized void test () 与public synchronized void run()形式的同步锁,采用前两种的表现形式作为比较项:

  一、首先验证public synchronized void run()

    

      public class MainClass implements Runnable{

        public int num = 100;
        public boolean flag = true;
        public boolean isFlag() {
          return flag;
        }
        public void setFlag(boolean flag) {
          this.flag = flag;
        }

        @Override
        public void run() {

          if (flag) {
            while (true) {
              synchronized (this) {//同步代码块
              if(num>0){
                try {
                  Thread.sleep(100);
                } catch (InterruptedException e) {

                  e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"1--------"+num--);
                }

              }

            }
          } else {
             while (true) {
                this.salt();

              }
          }

        }

        public synchronized void salt(){
           if(num > 0){
             try {
                Thread.sleep(100);
              } catch (InterruptedException e) {

                e.printStackTrace();
              }
              System.out.println(Thread.currentThread().getName()+"2....."+num--);
            }

          }

        public static void main(String[] args) {
          MainClass main = new MainClass();
          HashMap<String, Thread> hashMap = new HashMap<>();

          //实例化thread对象,并放到hashmap中
          for (int i = 0; i < 10; i++) {
            Thread threadq = new Thread(main);
            hashMap.put("thread for all "+ i, threadq);

          }

          //遍历hashmap,依次开启线程
          Iterator<Entry<String, Thread>> Iterator = hashMap.entrySet().iterator();
          while (Iterator.hasNext()) {
            try {
              Thread.sleep(10);
            } catch (InterruptedException e) {

              e.printStackTrace();
            }
            Thread thread = Iterator.next().getValue();
            thread.start();
            if(main.isFlag()){
              main.setFlag(false);
            }else{
              main.setFlag(true);
            }
          }

        }

}

输出结果:

Thread-02.....100
Thread-02.....99
Thread-02.....98
Thread-91--------97
Thread-82.....96
Thread-82.....95
Thread-82.....94
Thread-71--------93
Thread-62.....92
Thread-51--------91
Thread-42.....90
Thread-42.....89
Thread-31--------88
Thread-22.....87
Thread-11--------86
Thread-11--------85
Thread-11--------84
Thread-11--------83
Thread-22.....82
Thread-22.....81
Thread-31--------80
Thread-42.....79
Thread-51--------78
Thread-62.....77
Thread-62.....76
Thread-71--------75
Thread-71--------74
Thread-71--------73
Thread-82.....72
Thread-82.....71
Thread-82.....70
Thread-91--------69
Thread-02.....68
Thread-02.....67
Thread-91--------66
Thread-82.....65
Thread-82.....64
Thread-82.....63
Thread-82.....62
Thread-82.....61
Thread-82.....60
Thread-82.....59
Thread-82.....58
Thread-82.....57
Thread-82.....56
Thread-82.....55
Thread-71--------54
Thread-62.....53
Thread-62.....52
Thread-62.....51
Thread-51--------50
Thread-51--------49
Thread-42.....48
Thread-42.....47
Thread-42.....46
Thread-42.....45
Thread-31--------44
Thread-22.....43
Thread-11--------42
Thread-22.....41
Thread-22.....40
Thread-31--------39
Thread-31--------38
Thread-31--------37
Thread-31--------36
Thread-31--------35
Thread-31--------34
Thread-31--------33
Thread-31--------32
Thread-31--------31
Thread-42.....30
Thread-51--------29
Thread-51--------28
Thread-51--------27
Thread-51--------26
Thread-51--------25
Thread-51--------24
Thread-62.....23
Thread-62.....22
Thread-62.....21
Thread-62.....20
Thread-71--------19
Thread-71--------18
Thread-71--------17
Thread-82.....16
Thread-91--------15
Thread-02.....14
Thread-02.....13
Thread-91--------12
Thread-82.....11
Thread-82.....10
Thread-82.....9
Thread-82.....8
Thread-71--------7
Thread-71--------6
Thread-62.....5
Thread-62.....4
Thread-51--------3
Thread-42.....2
Thread-31--------1

  二、验证public static synchronized void run()锁

public class MainStaticClass implements Runnable {
  private static int num ;
  private boolean flag = true;
  private static CountDownLatch lanch;
  public MainStaticClass(int num1,CountDownLatch lanch1){
    lanch = lanch1;
    num = num1;
  }
  public boolean isFlag() {
    eturn flag;
  }
  public void setFlag(boolean flag) {
    this.flag = flag;
  }
  @Override
  public void run() {
    if (flag) {
      while (true) {
        synchronized (this.getClass()) {
          if(num>0){
            try {
              Thread.sleep(100);
            } catch (InterruptedException e) {

              e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"-1----------"+num--);
            lanch.countDown();
          }
        }
      }
    } else {
      while(true){
        salt();
      }
    }
  
  }
  public static synchronized void salt(){
    if(num>0){
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {

        e.printStackTrace();
      }
      System.out.println(Thread.currentThread().getName()+"-2----------"+num--);
      lanch.countDown();
    }
  }
  public static void main(String[] args) {

    CountDownLatch countDownLatch = new CountDownLatch(100);
    MainStaticClass main = new MainStaticClass(100,countDownLatch);
    HashMap<String, Thread> hashMap = new HashMap<>();
    for (int i = 0; i < 10; i++) {
      Thread threadq = new Thread(main);
      hashMap.put("thread for all "+ i, threadq);
    }
    Iterator<Entry<String, Thread>> Iterator = hashMap.entrySet().iterator();
    while (Iterator.hasNext()) {
      try {
        Thread.sleep(10);
      } catch (InterruptedException e) {

        e.printStackTrace();
      }
      Thread thread = Iterator.next().getValue();
      thread.start();
      if(main.isFlag()){
      main.setFlag(false);
      }else{
        main.setFlag(true);
      }
    }
    try {
      countDownLatch.await();
    } catch (InterruptedException e) {

      e.printStackTrace();
    }
    MainStaticClass main1 = new MainStaticClass(100,countDownLatch);
    for (int i = 0; i < 10; i++) {
      Thread threadq = new Thread(main1);
      hashMap.put("thread for all "+ i, threadq);
    }
    Iterator<Entry<String, Thread>> Iterator1 = hashMap.entrySet().iterator();
    while (Iterator1.hasNext()) {
    try {
      Thread.sleep(10);
    } catch (InterruptedException e) {

      e.printStackTrace();
    }
    Thread thread = Iterator1.next().getValue();
    thread.start();
    if(main1.isFlag()){
      main1.setFlag(false);
    }else{
      main1.setFlag(true);
    }
  }
  }
}

  

synchronized 同步函数的竞争关系验证的更多相关文章

  1. JAVA之旅(十三)——线程的安全性,synchronized关键字,多线程同步代码块,同步函数,同步函数的锁是this

    JAVA之旅(十三)--线程的安全性,synchronized关键字,多线程同步代码块,同步函数,同步函数的锁是this 我们继续上个篇幅接着讲线程的知识点 一.线程的安全性 当我们开启四个窗口(线程 ...

  2. java基础知识回顾之java Thread类学习(六)--java多线程同步函数用的锁

    1.验证同步函数使用的锁----普通方法使用的锁 思路:创建两个线程,同时操作同一个资源,还是用卖票的例子来验证.创建好两个线程t1,t2,t1线程走同步代码块操作tickets,t2,线程走同步函数 ...

  3. JAVA之旅(十四)——静态同步函数的锁是class对象,多线程的单例设计模式,死锁,线程中的通讯以及通讯所带来的安全隐患,等待唤醒机制

    JAVA之旅(十四)--静态同步函数的锁是class对象,多线程的单例设计模式,死锁,线程中的通讯以及通讯所带来的安全隐患,等待唤醒机制 JAVA之旅,一路有你,加油! 一.静态同步函数的锁是clas ...

  4. 『审慎』.Net4.6 Task 异步函数 比 同步函数 慢5倍 踩坑经历

    异步Task简单介绍 本标题有点 哗众取宠,各位都别介意(不排除个人技术能力问题) —— 接下来:我将会用一个小Demo 把 本文思想阐述清楚. .Net 4.0 就有了 Task 函数 —— 异步编 ...

  5. Net4.6 Task 异步函数 比 同步函数 慢5倍 踩坑经历

    Net4.6 Task 异步函数 比 同步函数 慢5倍 踩坑经历 https://www.cnblogs.com/shuxiaolong/p/DotNet_Task_BUG.html 异步Task简单 ...

  6. java 中多线程的同步函数的运用

    /* * 需求: * 银行有一个金库 * 有两个储户,分别存300元.每次存100 , 存三次 * * 这个是有线程问题的, * * 我们应该通过下边的三个方法来查找问题 * 1.明确哪些代码是多线程 ...

  7. Java多线程--同步函数

    /*需求:银行有一个金库有两个储户分别存300元 每次存100元,存3次 目的:该程序是否有安全问题,如果有,如何解决? 如何找问题(很重要)1.明确哪些代码是多线程运行代码2.明确共享数据3.明确多 ...

  8. 多线程---静态同步函数的锁是class(转载)

    /** 如果同步函数被静态修饰,那么他的锁就是该方法所在类的字节码文件对象 类名.class 静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象. 该对象就是:类名.class   ...

  9. 多线程---同步函数的锁是this(转载)

    class Ticket implements Runnable { private int tick = 100; Object obj = new Object(); boolean flag = ...

随机推荐

  1. Oracle数据库ORA-01109 数据库未打开

    引致 https://blog.csdn.net/colinmok/article/details/39504879?locationNum=11&fps=1  感谢! 在plsql创建了2表 ...

  2. 怎么精确控制solidworks里面的表格的位置

    手工移动是不可能的,总是有点误差,虽然有主动捕捉的功能. public void SetTablePosition(TableAnnotation table, double x, double y) ...

  3. RAND函数和SRAND函数

    首先我们要对rand&srand有个总体的看法:srand初始化随机种子,rand产生随机数,下面将详细说明. rand(产生随机数) 表头文件: #include<stdlib.h&g ...

  4. 编译在docker alpine中可用的go程序

    get docker image docker pull golang build docker run -it --rm -v `pwd`:/root/src -w /root/src golang ...

  5. c++界面库方案

    最近的开发需要向java以及c++方向转向:看了些java和c++的东西 最近研究了下,最后觉得使用ogre+mygui来实现c++界面,这样用比较方便: 当前ogre,mygui都可以实现界面,可以 ...

  6. Vue 表格里的下拉列表

    下拉列表column-select.vue组件内容: <template> <div class="column-select-wrapper"> < ...

  7. java 日志脱敏框架 sensitive-新版本0.0.2-深度拷贝,属性为对象和集合的支持

    项目介绍 日志脱敏是常见的安全需求.普通的基于工具类方法的方式,对代码的入侵性太强.编写起来又特别麻烦. 本项目提供基于注解的方式,并且内置了常见的脱敏方式,便于开发. 用户也可以基于自己的实际需要, ...

  8. 微信公众号openid处理的一些笔记

    每个用户对每个公众号的OpenID是唯一的.对于不同公众号,同一用户的openid不同.如果公司有多个公众号,可以通过开放平台关联,这样同一用户,对同一个微信开放平台下的不同应用,unionid是相同 ...

  9. NumPy基础

    一.NumPy ndarray (一)生成ndarray 表 数组生成函数 函数 描述(默认数据类型是float64) array 将输入数据(序列型对象)转换为ndarray,若不显示的指定数据类型 ...

  10. 创建只读账号oracle

    1.创建用户,指定哪个表空间create user test2 identified by "123" default tablespace BDCDJ_XC temporary ...