概述
这里记录 Java 多线程实现的三种方式。
实现 Runnable 接口
第一种方式,实现 Runnable 接口,实现 run 方法,然后用 Thread 类实例化,最后调用其 start 方法,代码如下。
class RunnableDemoTest implements Runnable {
private String name;
RunnableDemoTest(String name) {
this.name = name;
}
public void run() {
try {
for (int i=0; i<5; i++) {
System.out.println(name + " run: " + i);
Thread.sleep(100); // 100ms = 0.1s
}
} catch(InterruptedException e) {
System.out.println("Something wrong!");
}
}
}
public class MyRunnableDemo {
public static void main(String[] args) {
RunnableDemoTest th1 = new RunnableDemoTest("Thread One");
RunnableDemoTest th2 = new RunnableDemoTest("Thread Two");
new Thread(th1).start();
new Thread(th2).start();
}
}
继承 Thread 类
第二种方式,继承 Thread 类,需要重写 run 方法,此时不需要再单独用 Thread 类实例化,代码如下。
class ThreadDemoTest extends Thread {
private String name;
ThreadDemoTest(String name) {
this.name = name;
}
public void run() {
try {
for (int i=0; i<5; i++) {
System.out.println(name + " run: " + i);
Thread.sleep(100);
}
}catch (InterruptedException e) {
System.out.println("Something wrong!");
}
}
}
public class MyThreadDemo {
public static void main(String[] args) {
new ThreadDemoTest("Thread One").start();
new ThreadDemoTest("Thread Two").start();
}
}
使用 Callable + FutureTask
第三种方式,首先实现 Callable 接口,实现其 call 方法,之后用 FutureTask 类进行包装,最后再用 Thread 类实例化。使用此种方法的需求之一就是因为其可以在线程中返回值,代码如下。
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
class FutureDemoTest implements Callable<Integer> {
private String name;
FutureDemoTest(String name) {
this.name = name;
}
public Integer call() {
try {
for (int i=0; i<5; i++) {
System.out.println(name + " run:" + i);
Thread.sleep(100);
}
}catch (InterruptedException e) {
System.out.println("Something wrong!");
}
return 1;
}
}
public class MyFutureDemo {
public static void main(String[] args) {
FutureDemoTest th = new FutureDemoTest("Thread");
FutureTask<Integer> ft = new FutureTask<>(th);
new Thread(ft).start();
try {
System.out.println(ft.get()); // 获取返回值
}catch (Exception e) {
System.out.println("Something wrong!");
}
}
}
总结
不忘初心,砥砺前行!