Reputation: 1159
I have simple problems with MT in java. I woudlike to synchronize acces to console. An example: first thread write in System.out "Number one" Thread2 printl("Number two"). I woud like to synchronize this thread writing sequentially numer in console without buffering. How do this?
Thread one
Thread two
Thread one
Thread two
...
//Code
package com.example;
public class MyThread implements Runnable{
@Override
synchronized public void run(){
while(true){
System.out.println("Thread first");
}
}
}
//
package com.example;
public class MyThread2 implements Runnable {
@Override
synchronized public void run() {
// TODO Auto-generated method stub
System.out.println("");
}
}
//
package com.example;
import java.util.concurrent.Semaphore;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread th1= new Thread(new MyThread());
Thread th2= new Thread(new MyThread2());
th2.setPriority(Thread.MAX_PRIORITY);
th1.start();
th2.start();
}
}
Upvotes: 0
Views: 1139
Reputation: 30216
Well it's a rather useless question I fear, because if we want a sequential ordering threads are rather useless, but oh well, here's one solution: Assume we have N threads.
Thread 0 should write number 0, N, 2N, 3N,..
Thread 1 should write number 1, N+1, 2N+1, 3N+1
well you get the pattern. How to do this? Simple enough, we basically just need a method that waits until it's our turn to write. The real simple solution with static objects for simplicity:
private static volatile int globalVal = 0;
private static Object lock = new Object();
public void writeInt(int val) {
synchronized(lock) {
while (globalVal != val) {
try {
lock.wait();
}
catch(InterruptedException e) {
}
}
System.out.println(val);
globalVal++;
lock.notifyAll();
}
}
the logic in the threads itself is left as an exercise for the reader.
Upvotes: 2
Reputation: 21241
Use a Queue<String>
and add the String
s to the queue. Then have a dedicated thread taking from the queue and writing it to the console. This will create a FIFO ordering based on the queue access of the threads.
If you don't want to use queues, you should something like a token manager that switches through the blocked threads. An Exchanger<V>
for each participating thread would be a good starting point.
Upvotes: 0