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);
    }
  }
  }
}

  

posted on 2018-05-08 15:57  小成—编程路上的流浪者  阅读(578)  评论(0编辑  收藏  举报