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();
}
}
最后
以上就是大力树叶最近收集整理的关于起三个线程依次读取一个数组的数据,同时只有一个线程执行?的全部内容,更多相关起三个线程依次读取一个数组内容请搜索靠谱客的其他文章。
发表评论 取消回复