zoukankan      html  css  js  c++  java
  • synchronized(九)

    在Java中是有常量池缓存的功能的,就是说如果我先声明了一个String str1 = “a”; 再声明一个一样的字符串的时候,取值是从原地址去取的,也就是说是同一个对象。这也就导致了在锁字符串对象的时候,可以会取得意料之外的结果(字符串一样会取得相同锁)。

    package com.bjsxt.base.sync006;
    /**
    * synchronized代码块对字符串的锁,注意String常量池的缓存功能,
    * @author alienware
    *
    */
    public class StringLock {

    public void method() {
    //new String("字符串常量")
    synchronized ("字符串常量") {
    try {
    while(true){
    System.out.println("当前线程 : " + Thread.currentThread().getName() + "开始");
    Thread.sleep(1000);
    System.out.println("当前线程 : " + Thread.currentThread().getName() + "结束");
    }
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }

    public static void main(String[] args) {
    final StringLock stringLock = new StringLock();
    Thread t1 = new Thread(new Runnable() {

    public void run() {
    stringLock.method();
    }
    },"t1");
    Thread t2 = new Thread(new Runnable() {

    public void run() {
    stringLock.method();
    }
    },"t2");

    t1.start();
    t2.start();
    }
    }

    运行结果:

    当前线程 : t1开始
    当前线程 : t1结束
    当前线程 : t1开始
    当前线程 : t1结束
    当前线程 : t1开始

    。。。。。。。。

    改为synchronized (new String("字符串常量"))之后,运行结果:

    当前线程 : t1开始
    当前线程 : t2开始
    当前线程 : t2结束
    当前线程 : t1结束
    当前线程 : t1开始
    当前线程 : t2开始

    。。。。。。。。

  • 相关阅读:
    Eclipse安装反编译插件
    关于eclipse发送到桌面快捷方式后打不开
    字符串 242.有效的字符异位词
    栈 503.下一个更大的元素
    eclipse导入jar包
    Java获取当前的时间
    链表 24.两两交换链表中的节点
    链表 19.删除链表倒数第N个节点
    共享空间的栈
    栈的顺序存储结构
  • 原文地址:https://www.cnblogs.com/tsdblogs/p/8761030.html
Copyright © 2011-2022 走看看