0

我最近开始学习 Java,现在我在 uni 的并发编程课程中使用它是我选择的语言。

我一直在从事一项实验室任务,该任务需要我启动几个线程并按特定顺序运行它们。这是代码:

import java.util.concurrent.CountDownLatch;


class Lab1{

public static void main(String[] args){

    CountDownLatch leftLatch = new CountDownLatch(3);
    CountDownLatch midLatch = new CountDownLatch(1);

    LabThread t1 = new LabThread();
    new Thread(t1).start();

    // (new Thread(new LabThread(new CountDownLatch(1),leftLatch,1))).start();
    // (new Thread(new LabThread(new CountDownLatch(0),leftLatch,2))).start();
    // (new Thread(new LabThread(new CountDownLatch(0),leftLatch,3))).start();
    // (new Thread(new LabThread(leftLatch,midLatch,4))).start();
 //     (new Thread(new LabThread(midLatch,new CountDownLatch(0),5))).start();
    // (new Thread(new LabThread(midLatch,new CountDownLatch(0),6))).start();
    // (new Thread(new LabThread(midLatch,new CountDownLatch(0),7))).start();
}
}

public class LabThread implements Runnable{

CountDownLatch waitLatch = null;
CountDownLatch decLatch = null;
int threadNr;

public LabThread(CountDownLatch waitLatch, CountDownLatch decLatch,int threadNr){
    this.waitLatch = waitLatch;
    this.decLatch = decLatch;
    this.threadNr = threadNr;
}

public void run(){
    try{
        this.waitLatch.await();
        this.decLatch.countDown();
    }catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println(threadNr);
}
}

当我尝试编译时,出现此错误:

Lab1.java:12: error: constructor Thread in class Thread cannot be applied to given types;
    new Thread(t1).start();
    ^
required: CountDownLatch,CountDownLatch,int
found: LabThread
reason: actual and formal argument lists differ in length
1 error

我知道这很不言自明,但我只是找不到解决方法。我尝试了很多东西:摆脱重载的构造函数,扩展 Thread 而不是实现 Runnable,任何我认为可以提供帮助的东西,但它只是不断地用同样的错误困扰我,而且它变得非常荒谬。如果您知道解决方案,请与我分享您的智慧!

PS:我知道我的逻辑可能有点缺陷,但我会在它编译后继续:)

编辑: *问题已解决*!显然我需要做的就是清理我的项目(删除类文件)并再次编译。非常感谢 Tom Hawtin-tackline 和 fazomisiek 建议我这样做。重新编译时,我没有意识到保留旧文件有任何影响。我的错 !:) 谢谢大家的建议,没想到这么快就得到了答复

4

2 回答 2

0

您的问题似乎有点混乱 - 抛出的异常不适合您的代码。但是,你应该使用这样的东西:

LabThread t1 = new LabThread(leftLatch, midLatch, 69);
new Thread(t1).start();

(但你需要考虑你想要实现的逻辑,即运行多少线程、何时运行等)

顺便说一句:您确定要在编译之前保存文件吗?(这个错误是意外的)

BTW2:你应该在你的构造函数中调用 super() (你应该调用父类的构造函数——这是一个很好的做法)。

于 2013-10-24T09:26:35.720 回答
0

一旦定义了参数构造函数,就必须显式定义无参数构造函数。您的代码的问题是构造函数LabThread()不存在。

您可以执行以下操作之一。

  1. 定义无参数构造函数
  2. 使用带有三个参数的定义的构造函数。
  3. 删除三参数构造函数。
于 2013-10-24T09:29:57.417 回答