技术开发 频道

ThreadLocal与synchronized


    Java良好的支持多线程。使用java,我们可以很轻松的编程一个多线程程序。但是使用多线程可能会引起并发访问的问题。synchronized和ThreadLocal都是用来解决多线程并发访问的问题。大家可能对synchronized较为熟悉,而对ThreadLocal就要陌生得多了。

    并发问题。当一个对象被两个线程同时访问时,可能有一个线程会得到不可预期的结果。

    一个简单的java类Studnet
public class Student { private int age=0; public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } }
    一个多线程类ThreadDemo.
    这个类有一个Student的私有变量,在run方法中,它随机产生一个整数。然后设置到student变量中,从student中读取设置后的值。然后睡眠5秒钟,最后再次读student的age值。

public class ThreadDemo implements Runnable{ Student student = new Student(); public static void main(String[] agrs) { ThreadDemo td = new ThreadDemo(); Thread t1 = new Thread(td,"a"); Thread t2 = new Thread(td,"b"); t1.start(); t2.start(); } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { accessStudent(); } public void accessStudent() { String currentThreadName = Thread.currentThread().getName(); System.out.println(currentThreadName+" is running!"); // System.out.println("first read age is:"+this.student.getAge()); Random random = new Random(); int age = random.nextInt(100); System.out.println("thread "+currentThreadName +" set age to:"+age); this.student.setAge(age); System.out.println("thread "+currentThreadName+" first read age is:"+this.student.getAge()); try { Thread.sleep(5000); } catch(InterruptedException ex) { ex.printStackTrace(); } System.out.println("thread "+currentThreadName +" second read age is:"+this.student.getAge()); } }
    运行这个程序,屏幕输出如下:
    a is running!
    b is running!
    thread b set age to:33
    thread b first read age is:33
    thread a set age to:81
    thread a first read age is:81
    thread b second read age is:81
    thread a second read age is:81

    需要注意的是,线程a在同一个方法中,第一次读取student的age值与第二次读取值不一致。这就是出现了并发问题。
0
相关文章