y987425112 commented on issue #145: Adding volatile keywords to member variables
URL: https://github.com/apache/tomcat/pull/145#issuecomment-470503719
 
 
   package com.ydy.thread.volatile2;
   
   public class VolatileTest2 {
        public static void main(String[] args) {
                Task task = new Task();
                Thread t1 = new Thread(new Runnable() {
   
                        @Override
                        public void run() {
                                // TODO Auto-generated method stub
                                while (true) {
                                        task.add();
                                }
   
                        }
                });
                Thread t2 = new Thread(new Runnable() {
   
                        @Override
                        public void run() {
                                // TODO Auto-generated method stub
                                while (true) {
                                        task.print();
                                }
   
                        }
                });
                t1.start();
                t2.start();
   
        }
   
   }
   
   class Task {
        private int i = 0;
        private int j = 0;
        private Object lock = new Object();
   
        /**
         * add
         */
        public synchronized void add() {
                i++;
                j++;
        }
   
        public void print() {
                synchronized (lock) {
                        if (j > i) {
                                // If no instruction reordering occurs, this 
line of code will never run
                                System.out.println("Wrong result");
                        }
                }
   
        }
   
   }
   If no instruction reordering occurs, this line of code will never run 
`System.out.println("Wrong result");`

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org
For additional commands, e-mail: dev-h...@tomcat.apache.org

Reply via email to