public class ReadString {
private String[] read = {"1","2","3","4","5","6","7","8","9","10"};
public synchronized void read(int id ,int index){
if(index > 9)
return;
System.out.print("Thread :"+id+" read String :"+ read[index]+" \n");
}
}
public class ReadThread extends Thread {
private int threadId;
private ReadString reads;
private Object lock;
private final int COUNT = 3;
public static volatile int flag = 0;
public ReadThread(int id ,ReadString read,Object lock){
this.threadId = id;
this.reads = read;
this.lock = lock;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
synchronized (lock) {
if((flag%COUNT) == threadId){
reads.read(threadId,flag);
flag++;
lock.notifyAll();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
public class TestMain {
public static ReadString read;
public static void main(String[] args){
Object lock = new Object();
read = new ReadString();
new ReadThread(0,read,lock).start();
new ReadThread(1,read,lock).start();
new ReadThread(2,read,lock).start();
}
}