[英]java how to overload run() method
我有這樣的代碼,如何讓兩個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
實現, Task1
和Task2
:
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();
請記住,您可以隨意在Thread子類中重載run()方法。
public class FirstThread extends Thread{
public static void main(String[] args) {
FirstThread ft1= new FirstThread();
ft1.start(); // Seperate call stack
ft1.run("With parameter"); // same call stack
}
public void run(){
System.out.println("Thread is running");
}
public void run(String s){
System.out.println("Overloaded Thread is running " +s );
}
}
除非您自己調用,否則Thread類將忽略重載的run(String s)方法。 Thread類需要一個不帶參數的run()方法,並且在線程啟動后,它將在單獨的調用堆棧中為您執行此方法。 使用run(String s)方法,Thread類不會為您調用該方法,即使您自己直接調用該方法,也不會在具有單獨調用堆棧的新執行線程中執行該操作。 它將與您進行調用的代碼在同一調用堆棧中發生,就像其他常規方法調用一樣。
來源:SCJP 1.6 Kathy Siera(第9章:線程,部分:定義線程)
現在,根據您的需求,使用兩個類實現Runnable接口,並在單獨的調用堆棧上調用2個線程。 使用任何一個線程調用run(String)方法,它將在不同的調用堆棧上執行您的方法。
public class SeacondThreadRunnable {
public static void main(String[] a){
Thread myThread1= new Thread(new MyRunnable());
Thread myThread2= new Thread(new MyRunnable2());
myThread1.start();
myThread2.start();
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("Runnable run method called " +Thread.currentThread().getName());
run(" Overloaded Thread is running " ); // calling overloaded run method
}
public void run(String s){
System.out.println( Thread.currentThread().getName() + s);
}
}
class MyRunnable2 implements Runnable{
@Override
public void run() {
System.out.println("Runnable run method called " +Thread.currentThread().getName());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.