Can FairSync guarantee the order of execution?

a student :

My first question, Thank for your help! I'm trying to print odd and even numbers 1~100 alternatively using two threads. Expected results:

    pool-1-thread-1=> 1
    pool-1-thread-2=> 2
    pool-1-thread-1=> 3
    pool-1-thread-2=> 4
    ......
    pool-1-thread-1=> 99
    pool-1-thread-2=> 100

I think i can use FairSync, but it can only guarantee that most of the print is correct. like this:

pool-1-thread-1=> 55
pool-1-thread-2=> 56
pool-1-thread-1=> 57
pool-1-thread-2=> 58   
pool-1-thread-2=> 59  //※error print※
pool-1-thread-1=> 60
pool-1-thread-2=> 61
pool-1-thread-1=> 62

I don't know why is the order lost in very few cases? You can criticize my code and my English. Here is my code:

private static final int COUNT = 100;

private static final int THREAD_COUNT = 2;

private static int curr = 1;

static ReentrantLock lock = new ReentrantLock(true);

static ExecutorService executorService = Executors.newCachedThreadPool();

public static void main(String[] args) {
    Runnable task = () -> {
        for (; ; ) {
            try {
                lock.lock();
                if (curr <= COUNT) {
                    System.out.println(Thread.currentThread().getName() + "=> " + curr++);
                } else {
                    System.exit(0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    };
    for (int i = 0; i < THREAD_COUNT; i++) {
        executorService.execute(task);
    }
}
Geek :

No dear your implementation is not correct. Which thread get's the opportunity to RUN is decided by the OS. Thread 1 & 2 will execute one after another cannot be guaranteed.

You can fix your code by checking the previous value of the variable curr and if the value is not what this thread expects don't increment and print.

for eg :

if(curr.threadName.equals("Thread 2") && (curr%2 !=0))
{
// Print
// Increment
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=161472&siteId=1