zoukankan      html  css  js  c++  java
  • 浅谈synchronized作用

      在开辟多个线程时候,synchronized将会发挥它的作用,下面写个测试Demo进行观察它的作用:

    FirstThread runnThread = new FirstThread();
    Thread thread1 = new Thread(runnThread);
    Thread thread2 = new Thread(runnThread);
    thread1.setName("线程A");
    thread2.setName("线程B");
    thread1.start();
    thread2.start();

    public static class FirstThread implements Runnable{
    @Override
    public void run() {
    //synchronized (this) {
    for (int i = 10; i > 0; i--) {
    System.out.println(Thread.currentThread().getName()+i);
    //}
    }
    }
    }

    这是在进程里开启了两个线程,并且开启子线程的程序是同一个的。运行程序显示结果:

    线程B10
    线程A10
    线程B9
    线程A9
    线程B8
    线程A8
    线程B7
    线程A7
    线程B6
    线程B5
    线程B4
    线程B3
    线程B2
    线程B1
    线程A6
    线程A5
    线程A4
    线程A3
    线程A2
    线程A1

    可以看到即便线程B或者A运行时候,仍然会有另外一个线程抢占起来,占领线程,两个线程互相争抢。

    但是加上synchronized (this) {}这句话同步锁,运行结果:

    线程A10
    线程A9
    线程A8
    线程A7
    线程A6
    线程A5
    线程A4
    线程A3
    线程A2
    线程A1
    线程B10
    线程B9
    线程B8
    线程B7
    线程B6
    线程B5
    线程B4
    线程B3
    线程B2
    线程B1

    可以发现是一个线程的程序运行完才能运行下一个线程,即便在线程A运行时候线程B已经可以运行了,但是由于同步锁的作用是运行中的线程运行结束之后才能其它线程,避免了线程互扰的情况。

  • 相关阅读:

    字符串比较
    String对象的简单方法(特别讲解length()方法的实现。
    Character类
    线性结构应用实例:多项式加法运算
    队列的顺序和链式存储实现
    堆栈用数组和用链表实现
    广义表和多重链表(十字链表)
    powerDesigner的name和comment转化
    jquery-validate
  • 原文地址:https://www.cnblogs.com/zpfwin/p/7091870.html
Copyright © 2011-2022 走看看