JAVA 并发编程随笔【七】线程安全与共享资源

来源:互联网 发布:it男装 编辑:程序博客网 时间:2024/05/16 05:05

一、局部变量是线程安全的,也就是说局部变量永远不会被多个线程共享‘’


二、局部对象如果不会被其它方法获得,也不会被非局部变量引用,那么我们就说这个对象是线程安全的;


三、对象的成员变量存储在堆上,如果多个线程同时访问一个对象的成员变量,那么对象就是非线程安全的。


package framework.yaomy.thread.model;import framework.yaomy.thread.example.NotThreadSafe;/** * @Description:TODO * @version 1.0 * @since JDK1.7 * @author yaomy * @company xxxxxxxxxxxxxx * @copyright (c) 2017 yaomy Co'Ltd Inc. All rights reserved. * @date 2017年9月6日 下午2:11:08 */public class MyRunnable implements Runnable{private NotThreadSafe notThreadSafe;public MyRunnable(NotThreadSafe notThreadSafe) {this.notThreadSafe = notThreadSafe;}@Overridepublic void run() {this.notThreadSafe.add("你好==");System.out.println("==============");}}


package framework.yaomy.thread.example;import framework.yaomy.thread.model.MyRunnable;/** * @Description:TODO * @version 1.0 * @since JDK1.7 * @author yaomy * @company xxxxxxxxxxxxxx * @copyright (c) 2017 yaomy Co'Ltd Inc. All rights reserved. * @date 2017年9月6日 下午1:59:02 */public class NotThreadSafe {private StringBuilder sb = new StringBuilder();public void add(String text){this.sb.append(text);}public static void main(String[] args) {NotThreadSafe sharedInstance = new NotThreadSafe();new Thread(new MyRunnable(sharedInstance)).start();new Thread(new MyRunnable(sharedInstance)).start();}}


原创粉丝点击