本文主要講述:多線程工具類之5種實作方式。
衆所周知,為提高程式執行效率和資源使用率,我們需要使用到多線程。
應用場景主要是:高并發;異步處理;定時任務;網絡爬蟲;網絡程式設計等等。
而實作多線程有5種方式。
1、繼承Thread類,重寫run方法
2、實作Runnable接口
3、實作Callable接口
3、使用定時器
4、建立線程池
下面将分享這5種實作方式的具體執行個體。
一、繼承Thread類
public class Thread1 extends Thread {
@Override
public void run() {
for(int i = 1; i < 100; i++){
System.out.println("線程1運作了" + i + "次");
}
}
public static void main(String[] args) {
//開啟線程1
Thread1 thread1 = new Thread1();
thread1.start();
//開啟主線程
for(int i = 1; i < 100; i++){
System.out.println("主線程線程運作了" + i + "次");
}
}
}
運作結果:
二、實作Runnable接口
public class Thread1 implements Runnable {
@Override
public void run() {
for(int i = 1; i < 100; i++){
System.out.println("線程1運作了" + i + "次");
}
}
public static void main(String[] args) {
//開啟線程1
Thread1 thread1 = new Thread1();
new Thread(thread1).start();
//開啟主線程
for(int i = 1; i < 100; i++){
System.out.println("主線程線程運作了" + i + "次");
}
}
}
運作結果:
繼承Thread類和實作Runnable接口,去實作多線程,代碼是非常類似的,但是Runnable會更勝一籌,因為它可以破除java單繼承的限制,并且能夠增加代碼的健壯性。
三、實作Callable接口
public class Thread1 {
//使用Callable建立線程計算100以内的奇數
public static void main(String[] args) throws Exception {
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i % 2 == 0 ? 0 : i;
}
return sum;
}
};
FutureTask<Integer> task = new FutureTask<>(callable);
Thread t = new Thread(task);
t.start();
System.out.println(task.get());
}
}
輸出:2500
四、使用定時器
public class Thread1 extends TimerTask {
private int id;
public Thread1(int id){
this.id = id;
}
@Override
public void run() {
System.out.println("線程" + id + "執行了一次");
}
public static void main(String[] args){
Timer timer = new Timer();
//線程1:3秒後開始執行,1秒鐘執行一次
timer.schedule(new Thread1(1), 1000,3000);
//線程2:2秒後立即執行,1秒鐘執行一次
timer.schedule(new Thread1(2), 1000,2000);
}
}
輸出結果:
五、建立線程池
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(() -> {
System.out.println("線程1執行開始...");
Thread.sleep(3000);
System.out.println("線程1執行結束...");
});
executorService.execute(() -> {
System.out.println("線程2執行開始");
Thread.sleep(1000);
System.out.println("線程2執行結束");
});
executorService.shutdown();
執行結果:
線程1執行開始...
線程2執行開始
線程2執行結束
線程1執行結束...
感謝您的閱讀,祝你生活愉快,永無加班~