输出多线程程序

时间:2016-08-04 16:04:36

标签: java multithreading

您好我正在尝试理解下面代码的输出。根据我的理解,第一和第二个线程的输出可能不同。但是当我多次执行下面的代码时,我仍然得到两个相同的值如果我错了或是对的话,可以请一些人说明。

package com.vikash.Threading;

public class ThreadLocalExample {

    public static class MyRunnable implements Runnable {

        @SuppressWarnings("unused")
        private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
        D d=new D();

        @Override
        public void run() {
            //threadLocal.set( (int) (Math.random() * 100D) );
            d.setX( (int) (Math.random() * 100D) );
            //System.out.println(Thread.currentThread().getName()+" "+threadLocal.get());
            System.out.println(Thread.currentThread().getName()+" "+d.getX());
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
            }
            //System.out.println(Thread.currentThread().getName()+" "+threadLocal.get());
            //System.out.println(Thread.currentThread().getName()+" "+d.getX());
        }
    }

    public static void main(String[] args) throws InterruptedException {

        MyRunnable sharedRunnableInstance = new MyRunnable();

        Thread thread1 = new Thread(sharedRunnableInstance);
        Thread thread2 = new Thread(sharedRunnableInstance);

        thread1.start();thread1.setName("First");
        thread2.start();thread2.setName("Second");;

        thread1.join(); //wait for thread 1 to terminate
        thread2.join(); //wait for thread 2 to terminate
    }
}

1 个答案:

答案 0 :(得分:1)

这是因为你没有在d上进行同步,所以会发生什么是线程1设置X值,然后线程2设置x值,然后线程1打印已经被线程2重置的值。同步块使得确保打印正确的值

synchronized (d) {
    d.setX((int) (Math.random() * 100D));
    System.out.println(Thread.currentThread().getName() + " " + d.getX());
}