简单说明:
1、生产者负责将字符串转换成int 数字放入BlockingQueue,失败就停止生产消费线程。
2、消费者从BlockingQueue获得数字,取平方根值,并累积值。如果有负数,失败!停止生产消费线程。
3、模拟一个生产者,2个消费者。为了能均衡对应,生产者每次暂停 10毫秒,消费每次暂停23 毫秒~~
代码:
public class ThreadTest {
private final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>( 5 );
/**计算结果**/
private final AtomicInteger atoInt = new AtomicInteger(0);
/**整个计算过程是否成功**/
private final AtomicBoolean isSuccess = new AtomicBoolean(true);
private Thread t1 = null;
private Thread t2 = null;
private Thread t3 = null;
private final CountDownLatch endGate = new CountDownLatch( 2 );
public static void main(String[] args) throws InterruptedException {
String[] data = new String[]{ "1", "1", "4", "9", "25", "36", "49", "64", "81", "144"};
ThreadTest test = new ThreadTest();
Producter p = test.new Producter(data);
Consumer c1 = test.new Consumer();
Consumer c2 = test.new Consumer();
test.t1 = new Thread(p);
test.t2 = new Thread(c1);
test.t3 = new Thread(c2);
test.start();
test.endGate.await();
if( test.isSuccess.get() ){
System.out.println( "计算结果:" + test.atoInt.get() );
}
else{
System.out.println( "计算过程中遇到错误!" );
}
}
private void start(){
t1.start();
t2.start();
t3.start();
}
private void stop(){
t1.interrupt();
t2.interrupt();
t3.interrupt();
}
private class Producter implements Runnable{
private final String[] data;
public Producter(String[] data) {
super();
this.data = data;
}
@Override
public void run() {
try {
for( String s : data ){
//System.out.println( "当前读取数:" + s );
int i = Integer.valueOf( s );
queue.put( i );
Thread.sleep( 10 );
}
queue.put( Integer.MAX_VALUE );
} catch (NumberFormatException e) {
e.printStackTrace();
isSuccess.set(false);
stop();
return;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
private class Consumer implements Runnable{
@Override
public void run() {
try {
while( !Thread.currentThread().isInterrupted() ){
int i = queue.take();
Thread.sleep( 23 );
//遇到错误值
if( i<0 ){
stop();
isSuccess.set(false);
break;
}
//结束标志
else if( i == Integer.MAX_VALUE ){
stop();
break;
}
//System.out.println( Thread.currentThread() + "当前queue获取数:" + i );
atoInt.addAndGet( (int)Math.sqrt(i) );
//System.out.println( atoInt.get() );
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
finally{
endGate.countDown();
}
}
}
}