Thread共享数据,线程安全测试、不安全测试

1.创建类继承Thread 

public class MyThredUnsafe extends Thread{
    private int count=5;

    /**
     * 线程不安全
     */
    @Override
    public void run(){
        super.run();
        count--;
        System.out.println(Thread.currentThread().getName()+"计算count="+count);
    }

    /**
     * 线程安全
     */
   /* @Override
    public synchronized void run(){
        super.run();
        count--;
        System.out.println(Thread.currentThread().getName()+"计算count="+count);
    }*/
}

2.测试方法

public class MainTest {
    public static void main(String[] args) {
        //线程不安全,共享数据
        MyThredUnsafe myThredUnsafe=new MyThredUnsafe();
        Thread threadA=new Thread(myThredUnsafe,"A");
        Thread threadB=new Thread(myThredUnsafe,"B");
        Thread threadC=new Thread(myThredUnsafe,"C");
        Thread threadD=new Thread(myThredUnsafe,"D");
        Thread threadE=new Thread(myThredUnsafe,"E");
        threadA.start();
        threadB.start();
        threadC.start();
        threadD.start();
        threadE.start();

    }
}

测试结果

4.线程安全需加锁 

     /**
     * 线程安全
     */
   @Override
    public synchronized void run(){
        super.run();
        count--;
        System.out.println(Thread.currentThread().getName()+"计算count="+count);
    }

测试结果

发布了50 篇原创文章 · 获赞 25 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/zhaolinxuan1/article/details/84067956