多线程共享数据-非线程安全示例
多线程共享数据-非线程安全示例
package com.stono.thread2; import java.util.concurrent.atomic.AtomicInteger; public class Page11 extends Thread{ private int count = 5; private AtomicInteger c2 = new AtomicInteger(5); @Override public void run() { super.run(); // 此处会出现非线程安全问题 count --; System.out.println("由 "+this.currentThread().getName()+" 计算, count= "+count); // 这个线程安全 c2.decrementAndGet(); System.out.println("由 "+this.currentThread().getName()+" 计算, AtomicInteger= "+c2.get()); } public static void main(String[] args) { Page11 page11 = new Page11(); Thread a = new Thread(page11, "A"); Thread b = new Thread(page11, "B"); Thread c = new Thread(page11, "C"); Thread d = new Thread(page11, "D"); Thread e = new Thread(page11, "E"); a.start(); b.start(); c.start(); d.start(); e.start(); } }
使用AtomicInteger可以实现线程安全处理,但是输出顺序不是固定的;
也可以在run()方法前面加上synchronized进行修饰;