自己练习写了一个多线程读一个字符串,但是没法退出,想请教两个问题
1.这种写法是我自己想出来,有没有更优雅一点的方法呢
2.线程间应该怎么通知结束信号然后退出的?
感觉多线程难用的原因因为需要全部理解才能用好,一个地方没理解好,就用不好
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
class Reader implements Runnable {
private int id;
private String[] queue;
private Object lock;
private volatile AtomicInteger index;
private int threads;
private volatile boolean done = false;
public Reader(int id, String[] queue, Object lock, AtomicInteger index,
int threads, Boolean done) {
this.id = id;
this.queue = queue;
this.lock = lock;
this.index = index;
this.threads = threads;
this.done = done;
}
public void run() {
while (!done) {
synchronized (lock) {
while (index.get() % threads != id)
try {
lock.wait();
} catch (Exception e) {
}
System.out.println("The id" + id + ": " + queue[index.get()]
);
if (index.incrementAndGet() == queue.length) {
done = true;
}
lock.notifyAll();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class MultiReading {
public static void main(String[] args) throws InterruptedException {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
String words[] = line.split("\s");
Boolean done = false;
Object lock = new Object();
AtomicInteger index = new AtomicInteger(0);
int threads = 3;
for (int i = 0; i < threads; i++) {
new Thread(new Reader(i, words, lock, index, threads, done))
.start();
}
}
}