近来学习新线程类,发现有个问题很奇怪,下面的代码注释掉TimeUnit.MICROSECONDS.sleep(2),线程可以结束
不注释掉,线程结束不了,为什么呢,我写的代码有没有问题?请教各位高手。
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class MyTest { public static void main(String[] args) throws InterruptedException {
//阻塞Queue,模拟生产者-消费者
LinkedBlockingQueue<Long> q = new LinkedBlockingQueue<Long>(100); new Thread(new Thread1(q)).start();
new Thread(new Thread1(q)).start();
new Thread(new Thread2(q)).start();
new Thread(new Thread2(q)).start();
new Thread(new Thread2(q)).start(); //10秒后结束线程
TimeUnit.SECONDS.sleep(10);
//发出结束信号
Thread1.stop = true;
Thread2.stop = true; }
}class Thread1 implements Runnable {
//结束信号
public static volatile boolean stop = false;
private LinkedBlockingQueue<Long> queue = null;
private static Long i = 0L;
private static AtomicLong count = new AtomicLong();
private Lock lock = new ReentrantLock(); public Thread1(LinkedBlockingQueue<Long> queue) {
this.queue = queue;
} public void run() {
while (!stop) {
//加锁,防止其他线程修改count
lock.lock();
try {
//原子性操作,自增
count.incrementAndGet();
i = count.longValue();

try {
//生产i放进阻塞Queue
queue.put(i);
// TimeUnit.MICROSECONDS.sleep(2);//为什么注释掉可以停止线程
System.out.println("生产者:"
+ Thread.currentThread().getName() + ": " + i); } catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
lock.unlock();
}
} }
}class Thread2 implements Runnable {
public static volatile boolean stop = false;
private LinkedBlockingQueue<Long> queue = null;
private static Long i = 0L; public Thread2(LinkedBlockingQueue<Long> queue) {
this.queue = queue;
} public void run() {
while (!stop) { try {
//消费i
i = queue.take();
System.out.println("消费者:" + Thread.currentThread().getName()
+ ": " + i); } catch (InterruptedException e) {
e.printStackTrace();
}
} }
}

解决方案 »

  1.   

    你的线程占满了cpu,根本轮不到其它的线程执行。还有不要在不同的线程去修改另一个线程在用的任何变量(包括静态的)。
    public void run(){
      while(...){
    //code
        Thread.sleep(1);//让线程休息一下,把cpu让给操作系统以执行其它进程和线程
      }
    }
      

  2.   


    不明白你的意思,我的线程有这句TimeUnit.MICROSECONDS.sleep(2)才停止不了,没有这句才可以停止。还有如果不修改stop变量
    怎么才能停止线程呢