Fix the code

Report a typo

Consider the following code with two threads: the main thread and one worker thread.

Both threads work with the same variable done. Sometimes they may not be able to see changes of the variable.

Choose the correct way to fix the code.

import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(final String[] args) throws Exception {
        ThreadSafe1 runnable = new ThreadSafe1();
        new Thread(runnable).start();

        TimeUnit.MICROSECONDS.sleep(10);
        runnable.cancel();

        System.out.println("Main thread says goodbye!");
    }

    public static class ThreadSafe1 implements Runnable {
        private boolean done; // sometimes changes are not visible

        @Override
        public void run() {
            long count = 0;
            while (!done) {
                count++;
            }
            System.out.println("Job's done! Count = " + count);
        }

        public void cancel() {
            done = true;
        }
    }
}
Select one option from the list
___

Create a free account to access the full topic