概述
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();
}
}
最后
以上就是大力树叶为你收集整理的起三个线程依次读取一个数组的数据,同时只有一个线程执行?的全部内容,希望文章能够帮你解决起三个线程依次读取一个数组的数据,同时只有一个线程执行?所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复