gpt4 book ai didi

java - 为什么主线程在启动第一个线程后等待?

转载 作者:行者123 更新时间:2023-11-29 04:48:40 26 4
gpt4 key购买 nike

我试图了解 CountDownLatch 的用法,下面是我在这里使用的代码,

DecrementRunnable.java

    package com.nirjhar.java.countdownlatchexample;

import java.util.concurrent.CountDownLatch;

public class DecrementRunnable implements Runnable {

private String name;
private CountDownLatch cdl;

public DecrementRunnable(String name, CountDownLatch cdl) {
this.name=name;
this.cdl=cdl;
}

@Override
public void run() {
System.out.println("in run method");
for (int i = 0; i < 6; i++) {
cdl.countDown();
System.out.println("counting down "+cdl.getCount());
}
//cdl.notifyAll();
System.out.println("Notified to all");
}
}

CountDownDemoThread.java

package com.nirjhar.java.countdownlatchexample;

import java.util.concurrent.CountDownLatch;

public class CountDownDemoThread extends Thread {

private CountDownLatch cdl;

public CountDownDemoThread(String name, CountDownLatch cdl) {
this.cdl=cdl;
setName(name);
}

@Override
public synchronized void start() {

System.out.println("Task completed ... waiting for other thread to complete their task");
try {
cdl.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Continuing my tasks ..");
}
}

主程序,

package com.nirjhar.java.countdownlatchexample;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {
public static void main(String[] args)
{
CountDownLatch cdl=new CountDownLatch(6);
Thread tDecrementThread=new Thread(new DecrementRunnable("Runnable", cdl));
CountDownDemoThread cddt=new CountDownDemoThread("thread", cdl);
cddt.start();
System.out.println("thread 1 started");
tDecrementThread.start();
}
}

在这个主程序中,我希望在线程一启动后打印“线程 1 已启动”这一行,但由于 cddt 线程中的 cdl.await() 语句中的等待语句,这里主线程被阻塞。只是想知道这背后的原因是什么?

最佳答案

在您的 CountDownThread 类中,我认为您想要覆盖 run() 方法而不是 start

代替

public synchronized void start() {

试试

public void run() {


原因

wait statement in cdl.await() statement in cddt thread. Just wanted to know what is the reason behind this?

在这种情况下,您已经覆盖了 Threadstart 方法,因此它不再像往常一样生成线程来执行代码。

因此没有生成线程,事实上 main 线程正在调用 cd1.await() 而不是 cd1 线程(你想要的)。这就是 main 线程被阻塞的原因。

关于java - 为什么主线程在启动第一个线程后等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36256449/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com