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();
}
}
本文介绍了一个使用Java实现的多线程同步读取字符串数组的案例。通过synchronized关键字和wait/notifyAll机制,确保了三个线程能够按预定顺序轮流读取字符串,展示了线程间的同步控制和资源共享。





