You can use semaphores to do this task
by setting odd semaphore and even semaphore to 1 and 0 respectively, at the beginning when both threads try to acquire the semaphore only odd semaphore let the thread to pass because it's initialized with 1. this way guarantees that the odd thread run before the even thread.
FileWriter fileWriter = new FileWriter("./text.txt");
Semaphore oddSem = new Semaphore(1);
Semaphore evenSem = new Semaphore(0);
List<Object> list = new ArrayList<>();
for odd thread, at first line try to acquire the oddSem and after getting one item from the list release the evenSem. this way even thread can now proceed.
Runnable oddWriter = () -> {
Object object;
do {
acquire(oddSem);
if (list.isEmpty()) {
evenSem.release();
break;
}
object = list.remove(0);
evenSem.release();
String value = String.format("%s %s
" , "Odd Thread:",object.toString());
writeToFile(fileWriter, value);
} while (true);
};
for the even thread do the opposite
Runnable evenWriter = () -> {
Object object;
do {
acquire(evenSem);
if (list.isEmpty()) {
oddSem.release();
break;
}
object = list.remove(0);
oddSem.release();
String value = String.format("%s %s
" , "Even Thread:",object.toString());
writeToFile(fileWriter, value);
} while (true);
};
and finally, start threads
Thread oddThread = new Thread(oddWriter);
Thread evenThread = new Thread(evenWriter);
oddThread.start();
evenThread.start();
try {
oddThread.join();
evenThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
fileWriter.close();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…