线程5怎么无法启动?

qq_15357533 2021-01-19 03:00:28

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; //终止线程
}
}
}
}
}
...全文
62 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_15357533 2021-01-19
  • 打赏
  • 举报
回复
谢谢啊 ,这么快就帮我找到问题了。
qybao 2021-01-19
  • 打赏
  • 举报
回复
Hello18.mLQ.poll(); //去掉这行线程5就能启动,或者把
// >= 3000L 改成30秒,这样5也能启动

你要知道,调用Hello18.mLQ.poll(); 之后,线程1和线程2就会走入if (!Hello18.mLQ.isEmpty()) 的else里,执行
if (System.currentTimeMillis() - refreshTime >= 3000L) {
can = false; //终止线程
}

你可以else的代码加个打印就清楚了
if (System.currentTimeMillis() - refreshTime >= 3000L) {
System.out.println(Thread.currentThread().getName() + "stop"); //看看线程是否会走到这里,
can = false; //如果走到这里,can被设为false,就算线程5启动了,也不会进入while(can)循环,所以看不到线程5打印的信息它就结束了
}
qybao 2021-01-19
  • 打赏
  • 举报
回复
Hello18.mLQ.poll(); //去掉这行线程5就能启动,或者把
// >= 3000L 改成30秒,这样5也能启动

你要知道,调用Hello18.mLQ.poll(); 之后,线程1和线程2就会走入if (!Hello18.mLQ.isEmpty()) 的else里,执行
if (System.currentTimeMillis() - refreshTime >= 3000L) {
can = false; //终止线程
}

你可以else的代码加个打印就清楚了
if (System.currentTimeMillis() - refreshTime >= 3000L) {
System.out.println(Thread.currentThread().getName() + "stop"); //看看线程是否会走到这里,
can = false; //如果走到这里,can被设为false,就算线程5启动了,也不会进入while(can)循环,所以看不到线程5打印的信息它就结束了
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧