gpt4 book ai didi

java如何重载run()方法

转载 作者:行者123 更新时间:2023-11-29 09:52:55 26 4
gpt4 key购买 nike

我有一些这样的代码,如何让两个 run() 方法与 start() 方法在不同的线程中运行?

 public class Test extends Thread{
@override
public void run(){
//do something

}
public void run(int i){
//do something

}

public static void main(String[] args) {
Test test=new Test();
// test.start()
// How Can I let the two run() methods run in different thread?

}

}

最佳答案

你想要两个独立的线程,你只需要实现Runnable。扩展线程意味着您想更改 Thread 的行为,而您并没有这样做。

每个线程都会做其他事情,所以有两个 Runnable 实现,Task1Task2:

class Task1 implements Runnable (){
public run(){
System.out.println("Runnable 1");
}
}

class Task2 implements Runnable (){
public run(){
System.out.println("Runnable 2");
}
}

// create two threads, one for each task
Thread t1 = new Thread(new Task1());
Thread t2 = new Thread(new Task2());

// start the threads (should print the two messages)
t1.start();
t2.start();

要为不同的 Runnable 实现使用不同的参数,请像这样使用构造函数:

class ParamTask implements Runnable (){
String someArg;
public ParamTask(String someArg){
this.someArg = someArg;
}

public run(){
System.out.println("Runnable argument was: " + this.someArg);
}
}

Thread argThread = new Thread(new ParamTask("this is a message"));

argThread.start();

关于java如何重载run()方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31084898/

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