在java语言中,多线程的实现一般有以下三种方式:
1)实现runnable接口,并实现该接口的run()方法。
以下是主要步骤:
①自定义类并实现Ruannable接口,实现run()方法。
②创建Thread对象,用实现Ruannable接口的独享作为参数实例化该Thread对象。
③调用Thread的start()方法;
class MyThread implements Runnable
{
//创建线程类
public void run(){
System.out.println("Thread Body");
}
}
public class Test
{
public static void main(String[] args){
MyThread thread = New MyThread();
Thread t = new Thread(thread);
t.start();//启动线程
}
}
2)继承Thread类,重写run方法。
class MyThread extends Thread{
public void run(){
System.out.println("Thread Body");
}
}
public class Test{
public static void main(String[] args){
MyThread thread = New MyThread();
thread.start();
}
}
3)实现Callable接口,重写call方法。
import java.util.concurrent.*;
public class CallableAndFuture { // 创建线程类
public static class CallableTest implements Callable<String> {
public String call() throws Exception { return "Hello World!";
}
}
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor(); // 启动线程
Future<String> future = threadPool.submit(new CallableTest());
try {
System.out.println("waiting thread to finish");
System.out.println(future.get()); // 等待线程结束,并获取返回结果
} catch (Exception e) {
e.printStackTrace();
}
}
}