码迷,mamicode.com
首页 > 其他好文 > 详细

关于synchronized关键字修饰的注意点

时间:2017-05-17 17:14:11      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:system   ack   str   rri   字符串常量   字符串   eth   read   nts   

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() {
@Override
public void run() {
stringLock.method();
}
},"t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
stringLock.method();
}
},"t2");

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

关于synchronized关键字修饰的注意点

标签:system   ack   str   rri   字符串常量   字符串   eth   read   nts   

原文地址:http://www.cnblogs.com/yuanchangcheng/p/6867940.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!