zoukankan      html  css  js  c++  java
  • java并发

    竞态条件示例:

    public class Client {
        public static void main(String[] args) throws InterruptedException {
            MyRunnable myRunnable = new MyRunnable();
            Thread thread1 = new Thread(myRunnable, "线程1");
            Thread thread2 = new Thread(myRunnable, "线程2");
            Thread thread3 = new Thread(myRunnable, "线程3");
    
            thread1.start();
            thread2.start();
            thread3.start();
    
    
            thread1.join();
            thread2.join();
            thread3.join();
    
            System.out.println(myRunnable.getA());
        }
    
    
    }
    
    class MyRunnable implements Runnable {
    
        private int a = 0;
    
        @Override
        public void run() {
            for (int i = 0; i < 100000; i++) {
                ++a;
            }
        }
    
        public int getA() {
            return a;
        }
    }
    
    

    输出结果不一定,与预期不符。

    解决方案1:内置锁,synchronized
    解决方案2:显示锁,lock。unlock要放在finally里。

  • 相关阅读:
    LoadRunner
    LoadRunner
    LoadRunner
    LoadRunner
    Python
    hadoop for .Net
    MVC初学
    MVC初学
    android学习---面试一
    android学习---progressbar和ratingbar
  • 原文地址:https://www.cnblogs.com/liyeliang/p/9859842.html
Copyright © 2011-2022 走看看