Multithreading weird behavior

Mohammad Rizwaan :

I have been going through some basic multithreading examples, and tried implementing some code to see how thread priorities work:

class PriorityThreading extends Thread {

private static boolean stop = false;
private int count = 0;

public PriorityThreading(String name) { 
    super(name);
}

public void run() {
    do {
        count++;
    }while(stop==false && count<10000000 );
    stop = true;
}

public static void main (String [] args) throws InterruptedException{
    PriorityThreading thread = new PriorityThreading("thread 1");
    PriorityThreading thread2 = new PriorityThreading("thread 2");
    PriorityThreading thread3 = new PriorityThreading("thread 3");
    
    
    thread.setPriority(MAX_PRIORITY);
    thread2.setPriority(NORM_PRIORITY);
    thread3.setPriority(MIN_PRIORITY);
    
    thread.start();
    thread2.start();
    thread3.start();
    
    thread.join();
    thread2.join();
    thread3.join();
    
    
    System.out.println(thread.getName() + " " + thread.count);
    System.out.println(thread2.getName() + " " + thread2.count);
    System.out.println(thread3.getName() + " " + thread3.count);
    
}
}

And I constantly get this output: thread 1 10000000 thread 2 10000000 thread 3 10000000

This output is very confusing to me as:

  1. I expected only 1 thread to have reached this total, due to the while loop having to be stopped after the first thread had finished and stop=true
  2. Secondly, I expected only thread1 with the highest priority to have reached the max total.

I would really appreciate any explanation of why this is occurring,

Thanks.

Charlie Armstrong :

You have thread priorities and all down perfectly. The only issue here is that stop doesn't necessarily have the same value on all threads. Each thread caches its own value for stop in thread-local memory. When one thread sets its value of stop to true, the other threads don't necessarily "see" that change. The fix is simple; just declare stop as volatile like so:

private static volatile boolean stop = false;

This keeps the variable in main memory, therefore forcing the threads to communicate with one another.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related