使用@non线程安全类有什么影响?

时间:2015-06-09 04:12:15

标签: thread-safety

我编写了以下代码,因为我试图了解使用ThreadLocals的情况: -

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestDF {
    private DateFormat df = new SimpleDateFormat("MM/dd/yy");

    public  String formatCurrentDate() {
        System.out.println(">>>>>>>"+Thread.currentThread().getName());
        Date d = new Date();
        return df.format(d);
    }

    public  String formatFirstOfJanyary1970() {
        System.out.println(">>>>>>>" + Thread.currentThread().getName());
        Date d = new Date(0);
        return df.format(d);
    }

    public static void main(String[] args) {
        TestDF df = new TestDF();
        Thread t1 = new Thread(new WorkerThread(df));
        Thread t2 = new Thread(new WorkerThread1(df));

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

    }

    public static class WorkerThread implements Runnable {
        TestDF df;

        public WorkerThread(TestDF df) {
            this.df = df;
        }

        @Override
        public void run() {
            Thread.currentThread().setName("Worker-Thread 1");
            System.out.println("Inside Thread1*");
            System.out.println("Thread 1 "+df.formatCurrentDate());
            System.out.println("Inside Thread1**");
            try {
                Thread.sleep(5000l);
                System.out.println("Inside Thread1***");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static class WorkerThread1 implements Runnable {
        TestDF df;

        public WorkerThread1(TestDF df) {
            this.df = df;
        }

        @Override
        public void run() {
            Thread.currentThread().setName("Worker-Thread 2");
            System.out.println("Inside Thread2*");
            System.out.println("Thread 2 "+df.formatFirstOfJanyary1970());
            System.out.println("Inside Thread2**");
            try {
                Thread.sleep(5000l);
                System.out.println("Inside Thread2***");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}

我收到的内容如下: -

Inside Thread1*
Inside Thread2*
>>>>>>>Worker-Thread 2
>>>>>>>Worker-Thread 1
Thread 1 06/09/15              <-- 
Thread 2 06/09/15              <--
Inside Thread1**
Inside Thread2**
Inside Thread1***
Inside Thread2***

我知道SimpleDateFormat不是线程安全的;但仍然无法弄清楚是怎么回事。

0 个答案:

没有答案