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. DATA 步数据纵向串接

    DATA A;A='1';RUN; %MACRO M_A();DATA B;SET %DO I=1 %TO 10;A%END;;RUN;%MEND; %M_A(); PROC PRINT DATA=B ...

  2. 织梦dede文章列表调用标签的用法和规则

    织梦dede列表标签在任何模板的网站中都可能会使用到,而且我们在仿站的时候也经常要使用到列表标签.这里主机吧就给大家讲一下文章列表以及图片列表.软件列表以及分类信息列表标签的用法,和结合div+css ...

  3. 我的第一个flutter程序

    环境搭建好了之后,终于可以开始flutter的学习,废话少说先开始‘Hello World’. 创建好flutter项目之后,打开设备模拟器 打开之后 准备ok,开始编码 -------------- ...

  4. 内核驱动程序中如何读写user space的文件,方便调试程序

    需要在Linux kernel--大多是在需要调试的驱动程序--中读写文件数据.但是在kernel中操作文件没有标准库可用,需要利用kernel的一些函数,这些函数主要有: filp_open() f ...

  5. python Excel数据导出

    import pymysql,os,time,xlwtpymysql.install_as_MySQLdb() try: #创建一个excel工作簿,编码utf-8,表格中支持中文 wb=xlwt.W ...

  6. Linux上安装jdk,mysql

    1.准备工作 一台纯净的Linux系统需要先安装一些依赖才能安装jdk等 rpm: 本地添加安装程序:rpm -ivh 程序名 本地查看程序: rpm -qa 本地卸载程序: rpm -e --nod ...

  7. 两个对象的 hashCode()或equals相同,equals或hashCode不一定相同--《案例演示》

    两个对象的 hashCode()或equals相同,equals或hashCode不一定相同 1.两个对象的equals相同,hashCode不一定相同 在重写equals方法,未重写hashCode ...

  8. setCapture 使用方法

    setCapture 可以捕获到 移动到浏览器外的鼠标事件. 例如拖动过程中,即使鼠标移动到了浏览器外,拖动程序依然可以执行! 作用就是把 把鼠标事件 捕获到 当前文档指定的对象! setCaptur ...

  9. python1.返回一个字符串中出现次数第二多的单词 2.字符串中可能有英文单词、标点、空格 3.字符串中的英文字符全部是小写

    import re from collections import Counter def second_count_word(s): # # 利用正则按标点和空格切割,有其他标点可以添加到[]内 # ...

  10. Taro开发写密码支付弹层

    在支付的时候弹出填写密码,模仿了支付宝支付填写密码.主要是利用遮罩的来实现.直接上代码吧. html设计,通过标记控制显示. { showPayPwdInput ? <View classNam ...