java多线程 future_Java多线程Future模式
package future;
import java.util.Date;
/**
* 服務器
*
* @author wpy
*
*/
public class Service {
/**
* 1.服務器的處理某個業務,該業務可以分成AB兩個過程,并且AB兩個過程之間不需要彼此的返回結果
* 2.A過程需要1秒鐘,B過程需要2秒鐘,主線程其他操作2秒鐘
*
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Service service = new Service();
long notUseFuture = service.notUseFuture();
System.out.println("==============================");
long useFuture = service.useFuture();
System.out.println("==============================");
System.out.println("notUseFuture整個業務耗時"+notUseFuture);
System.out.println("useFuture整個業務耗時"+useFuture);
}
public long useFuture() throws InterruptedException {
Date startOn = new Date();
String name = Thread.currentThread().getName();
final FutureDate futureDateA = new FutureDate<>();
final FutureDate futureDateB = new FutureDate<>();
Thread a = new Thread(new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + ":任務A開始執行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
futureDateA.setData(name + ":任務A執行結果");
System.out.println(name + ":任務A執行結束");
}
}, "線程A");
Thread b = new Thread(new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + ":任務B開始執行");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
futureDateB.setData(name + ":任務B執行結果");
System.out.println(name + ":任務B執行結束");
}
}, "線程B");
Date before = new Date();
a.start();
b.start();
Date after = new Date();
System.out.println(name + ":a,b阻塞主線程時間:"
+ (after.getTime() - before.getTime()));
// 假設其他業務執行兩秒鐘
Thread.sleep(2000);
before = new Date();
String dataA = futureDateA.getData();
after = new Date();
System.out.println(name + ":獲取A線程結果時間:"
+ (after.getTime() - before.getTime()));
before = new Date();
String dataB = futureDateB.getData();
after = new Date();
System.out.println(name + ":獲取線程結果時間:"
+ (after.getTime() - before.getTime()));
System.out.println(name + ":A線程結果:" + dataA);
System.out.println(name + ":B線程結果:" + dataB);
Date endOn = new Date();
/*System.out.println(name + "整個業務耗時"
+ (endOn.getTime() - startOn.getTime()));*/
return endOn.getTime() - startOn.getTime();
}
public long notUseFuture() throws InterruptedException {
Date startOn = new Date();
// 任務A
String name = Thread.currentThread().getName();
System.out.println(name + ":任務A開始執行");
Thread.sleep(1000);
System.out.println(name + ":任務A執行結束");
// 任務B
System.out.println(name + ":任務B開始執行");
Thread.sleep(3000);
System.out.println(name + ":任務B執行結束");
// 主線程其他操作
Thread.sleep(2000);
Date endOn = new Date();
return endOn.getTime() - startOn.getTime();
}
}
總結
以上是生活随笔為你收集整理的java多线程 future_Java多线程Future模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 山东大学 2020级数据库系统 实验五
- 下一篇: swoole 捕捉php错误,swool