1.将类声明为 Thread 的子类,该子类应重写 Thread 类的 run 方法
class MyThread extends Thread {
public void run() {
//线程中要执行的代码
. . .
}
}
创建并启动一个线程
MyThread t1 = new MyThread();
t1.start();
2.实现 Runnable 接口的类,实现 run 方法
class MyThread2 implements MyThread2 {
public void run() {
// 线程中要执行的代码
. . .
}
}
创建并启动一个线程:
MyThread2 t2 = new MyThread2 ();
new Thread(t2).start();
3.使用Callable和Future创建线程
call()方法将作为线程执行体,并且有返回值,调用FutureTask对象的get()方法来获得子线程执行结束后的返回值。
public class Test implements Callable<Integer>{
@Override
public Integer call() throws Exception {
int count =0;
for(int i=0;i<=10;i++){
count=count+i;
}
return count;
}
}
创建并启动一个线程:
Test test=new Test();
FutureTask<Integer> thread = new FutureTask<>(test);
new Thread(thread,"有返回值的线程").start();
System.out.println(thread.get());
本文介绍了Java中创建多线程的三种主要方法:继承Thread类并重写run方法;实现Runnable接口并实现run方法;使用Callable接口和Future获取线程返回值。每种方法都提供了详细的代码示例。

被折叠的 条评论
为什么被折叠?



