方法一:继承Thread类创建线程
Java中实现多线程的一种方式是继承Thread类。Thread类本质上是实现了Runnable接口的一个实例,代表一个线程的实例。启动线程的唯一方法就是通过Thread类的start()方法。 通
Java中实现多线程的一种方式是继承Thread类。Thread类本质上是实现了Runnable接口的一个实例,代表一个线程的实例。启动线程的唯一方法就是通过Thread类的start()方法。
通过继承Thread类并复写run()方法,我们可以自定义线程内的操作逻辑。例如:
public class MyThread extends Thread {
public void run() {
("()");
}
}
MyThread myThread1 new MyThread();
MyThread myThread2 new MyThread();
();
();
方法二:实现Runnable接口创建线程
如果自己的类已经继承了其他类,则无法直接继承Thread类。此时,可以实现Runnable接口来创建线程。
public class MyThread extends OtherClass implements Runnable {
public void run() {
("()");
}
}
MyThread myThread new MyThread();
Thread thread new Thread(myThread);
();
方法三:实现Callable接口通过FutureTask包装器来创建线程
如果希望线程执行完毕后返回结果,可以使用Callable接口配合FutureTask包装器来创建线程。
public class SomeCallableextends OtherClass implements Callable { @Override public V call() throws Exception { // TODO Auto-generated method stub return null; } } Callable oneCallable new SomeCallable (); FutureTask oneTask new FutureTask (oneCallable); Thread oneThread new Thread(oneTask); ();
方法四:使用ExecutorService、Callable、Future实现有返回结果的线程
ExecutorService、Callable、Future是JDK中实现多线程的一套接口,其中Callable接口用于定义有返回值的任务。通过将Callable任务提交给ExecutorService线程池,并使用Future对象获取任务的返回结果,就可以实现有返回结果的多线程。
import *;
import ;
import ;
import ;
@SuppressWarnings("unchecked")
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
("----程序开始运行----");
Date date1 new Date();
int taskSize 5;
ExecutorService pool (taskSize);
List> list new ArrayList>();
for (int i 0; i < taskSize; i ) {
Callable