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();
}
}
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:
the logic in the threads itself is left as an exercise for the reader.