在Java中创建新线程的方法有多少种?
2022-09-03 03:11:36
实际上,除了扩展 Thread 类和实现 Runnable 接口之外,还有哪些其他方法可用?
实际上,除了扩展 Thread 类和实现 Runnable 接口之外,还有哪些其他方法可用?
在Java中创建新线程的方法只有一种,那就是实例化java.lang.Thread
(要实际运行该线程,您还需要调用)。start()
在Java代码中创建线程的其他所有内容都回退到封面后面的这种方式(例如,ThreadFactory
实现将在某个时候实例化对象,...)。Thread
有两种不同的方法可以指定要在该线程中运行的代码:
java.lang.Runnable 并将
实现它的类的实例传递给 Thread
构造函数。run()
方法。Thread
第一种方法(实现)通常被认为是更正确的方法,因为您通常不会创建新的“种类”Thread,而只是想在专用线程中运行一些代码(即a)。Runnable
Runnable
线程主要可以通过3种不同的方式创建
class SampleThread extends Thread {
//method where the thread execution will start
public void run(){
//logic to execute in a thread
}
//let’s see how to start the threads
public static void main(String[] args){
Thread t1 = new SampleThread();
Thread t2 = new SampleThread();
t1.start(); //start the first thread. This calls the run() method.
t2.start(); //this starts the 2nd thread. This calls the run() method.
}
}
class A implements Runnable{
@Override
public void run() {
// implement run method here
}
public static void main() {
final A obj = new A();
Thread t1 = new Thread(new A());
t1.start();
}
}
class Counter implements Callable {
private static final int THREAD_POOL_SIZE = 2;
// method where the thread execution takes place
public String call() {
return Thread.currentThread().getName() + " executing ...";
}
public static void main(String[] args) throws InterruptedException,
ExecutionException {
// create a pool of 2 threads
ExecutorService executor = Executors
.newFixedThreadPool(THREAD_POOL_SIZE);
Future future1 = executor.submit(new Counter());
Future future2 = executor.submit(new Counter());
System.out.println(Thread.currentThread().getName() + " executing ...");
//asynchronously get from the worker threads
System.out.println(future1.get());
System.out.println(future2.get());
}
}
支持具有执行器框架的可调用接口,用于线程池。
可运行或可调用接口优先于扩展 Thread 类