多线程关键字volatile的使用,记录变量修改和统计

mac2024-03-23  33

主要是多线程下静态变量的值不能及时回写到运行内存上 用synchronized 或者lock 不加volatile的变量拿不到最新值 public class PersonOne implements Runnable { /* private static int count = 100; private static int tatol=0;*/ private volatile int count = 100; private volatile int tatol=0; ReentrantLock lock = new ReentrantLock(); @Override public void run() { while (count > 0) { try { //lock.lock(); sale(); } catch (Exception e) { e.printStackTrace(); } finally { // lock.unlock(); } } } //public synchronized void sale() { public void sale() { if (count > 0) { tatol+=count; count--; System.out.println(Thread.currentThread().getName() + "正在出售第" + (100 - count) + "票"); if (count==0){ System.out.println(tatol); } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] arg) { PersonOne personOne = new PersonOne(); Thread[] t = new Thread[10]; for (int i = 0; i < 10; i++) { t[i] = new Thread(personOne, "窗口" + i); t[i].start(); } } }

 

 

最新回复(0)