ran*_*arr 4 java multithreading thread-safety
当我们Subclass Thread时,我们是否覆盖它的run方法?我们知道Thread类本身实现了Runnable,但Runnable类中没有定义run方法的主体.
这是我脑海中的画面:
Runnable - 父类 - 它有一个run方法,空体.
线程 - 孩子,
classA扩展了Thread-Child of Child,
当我们在"classA"中定义run()方法时,我们是否重写在Runnable类中声明的run方法?感谢您的时间.
有两种方法可以定义线程的行为:子类Thread类,或实现Runnable接口.
对于第一种方式,只需扩展Thread类并使用您自己的实现覆盖run()方法:
public class HelloThread extends Thread {
@Override
public void run() {
System.out.println("Hello from a thread!");
}
}
public class Main {
// main method just starts the thread
public static void main(String args[]) {
(new HelloThread()).start();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,为Thread实现逻辑的首选方法是创建一个实现Runnable接口的类:
public class HelloRunnable implements Runnable {
@Override
public void run() {
System.out.println("Hello from a thread!");
}
}
public class Main {
// notice that we create a new Thread and pass it our custom Runnable
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Run Code Online (Sandbox Code Playgroud)
实现Runnable的首选原因是它提供了线程行为与线程本身之间的明确区分.例如,在使用线程池时,您实际上从不实际创建线程,只需将Runnable传递给框架,它将在可用的线程上为您执行:
public class Main {
public static void main(String args[]) {
int poolSize = 5;
ExecutorService pool = Executors.newFixedThreadPool(poolSize);
pool.execute(new HelloRunnable());
}
}
Run Code Online (Sandbox Code Playgroud)
进一步阅读:
| 归档时间: |
|
| 查看次数: |
11946 次 |
| 最近记录: |