62,614
社区成员
发帖
与我相关
我的任务
分享
public class Hello18 {
public static LinkedBlockingQueue<String> mLQ = new LinkedBlockingQueue<>();
public static void main(String[] args) {
Hello18.mLQ.offer("中国");
Thread thread1 = new Thread(new ARunnable(), "线程1");
thread1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Hello18.mLQ.poll(); //去掉这行或者把 refreshTime >= 3000L
//改为 30000L,线程1接着打印时,线程5也能启动
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Hello18.mLQ.offer("韩国");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(new ARunnable(), "线程5").start();
}
}
class ARunnable implements Runnable {
public static volatile boolean can = true;
@Override
public void run() {
int i = 0;
long refreshTime = System.currentTimeMillis();
while (can) {
if (!Hello18.mLQ.isEmpty()) {
refreshTime = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + " i = " + i);
i++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
if (System.currentTimeMillis() - refreshTime >= 3000L) {
can = false; //终止线程
}
}
}
}
}