直接繼承Thread類,重寫run方法
package snippet;
public class test {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new MyThread().start();
}
}
}
class MyThread extends Thread {
@Override
public void run() {
for (int i = 1; i < 100; i++) {
System.out.println(getName() + "--->" + i);
}
}
}
使用Runable接口+Thread
作為Thread 參數傳入(與上面沒有什么不同,只是為了減少設計的藕性)
package snippet;
public class test {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(new MyRunnable()).start();
}
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 1; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "--->" + i);
}
}
}
注意,當實現Runable接口并且覆寫Thread的run方法時,只會調用Thread的run方法.
使用Runable接口
使用Runable接口比較復雜,需要使用到
線程池
,但是它可以帶返回值
。
package snippet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<Integer> {
private int num1;
private int num2;
public MyCallable(int num1, int num2) {
try {
this.num1 = num1;
this.num2 = num2;
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Integer call() throws Exception {
return num1 + num2;
}
}
public class test {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newCachedThreadPool();
/**
* 創建一個線程池
*/
List<Future<Integer>> results = new ArrayList<>();
/**
* Future<T>是泛型接口,其中泛型為返回數據類型
*/
for (int i = 0; i < 5; i++) {
Future<Integer> result = pool.submit(new MyCallable(i, i + 1));
results.add(result);
}
for (int i = 0; i < results.size(); i++) {
System.out.println(results.get(i).get());
}
/**
* 使用get去獲取call方法返回的值,可設置超時. 因為有時候若等待時間太長,則造成體驗不好
*/
}
}