美文网首页
java 输出值导致多线程下输出正确

java 输出值导致多线程下输出正确

作者: JAVA弑云 | 来源:发表于2019-09-29 15:25 被阅读0次
    public class AddInteger {
    
        private int count = 0;
    
        void addCount() {
            int addcount = 0;
            System.out.println(Thread.currentThread().getId() + Thread.currentThread().getName());
            while (addcount++ < 100000) {
                count += 1;
    //            System.out.println(count);
            }
        }
    
        int getCount() {
            return this.count;
        }
    }
    
    
    public class MultithThread implements Runnable{
        private  AddInteger addInteger=null;
    
        public MultithThread(AddInteger addInteger) {
            this.addInteger = addInteger;
        }
    
        @Override
        public void run() {
            addInteger.addCount();
    
        }
    }
    
    public class TestThread {
        public static void main(String[] args) {
            AddInteger addInteger = new AddInteger();
            MultithThread multithThread1 = new MultithThread(addInteger);
            Thread thread = new Thread(multithThread1);
    
            Thread thread2 = new Thread(multithThread1);
            thread.start();
            thread2.start();
            try {
                thread.join();
                thread2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(addInteger.getCount());
        }
    }
    
    

    如上图所示
    如果addCount方法内的输出行被注释掉,则最终在主方法中输出的count会小于20000,接近10000,但如果将输出行取消注释,则一定是20000,这边想半天还是没想通,日后再想

    相关文章

      网友评论

          本文标题:java 输出值导致多线程下输出正确

          本文链接:https://www.haomeiwen.com/subject/kaifpctx.html