呼叫某個方法後,我們需要程式過一段時間再去處理,就可以用
多執行緒阻塞
或Timer定時器
來實現
方法一
多執行緒阻塞實現方式
MyTask
package abc;
import java.util.concurrent.*;
public class MyTask implements Callable<Integer> {
private int num;
private int price;
public MyTask(int num, int price) {
this.num = num;
this.price = price;
}
public int add(int m, int n) {
System.out.println("執行運算..."+"\n");
return m * n;
}
@Override
public Integer call() throws Exception {
//睡眠5秒
Thread.sleep(5 * 1000L);
return add(num,price);
}
}
複製程式碼
測試類
package abc;
import org.junit.Test;
import java.util.concurrent.FutureTask;
public class ThreadTest {
@Test
public void c() throws Exception {
MyTask task = new MyTask(10,20);
FutureTask<Integer> resultObject = new FutureTask<Integer>(task);
new Thread(resultObject).start();
//阻塞當前執行緒
int result = resultObject.get();
System.out.println(result);
}
}
複製程式碼
方法二
通過
Timer
定時器實現
TestTimerTask
package abc;
import java.util.Date;
import java.util.TimerTask;
public class TestTimerTask extends TimerTask {
private String username;
private int age;
public TestTimerTask(String username, int age) {
this.username = username;
this.age = age;
}
@Override
public void run() {
// 處理業務邏輯
System.out.println("開始處理.");
System.out.println("大家好,我叫" + username + ",今年" + age + "歲");
System.out.println("結束時間:"+new Date().toLocaleString());
System.gc();
cancel();
}
}
複製程式碼
測試類
package abc;
import java.util.Date;
import java.util.Timer;
public class TimerTest {
public static void main(String[] args) {
System.out.println("開始時間:"+new Date().toLocaleString());
Timer timer = new Timer();
System.out.println("一:"+timer);
timer.schedule(new TestTimerTask("張三",20),5000);
System.out.println(timer);
}
}
複製程式碼
輸出結果
開始時間:2018-11-8 17:21:49
一:java.util.Timer@6acbcfc0
java.util.Timer@6acbcfc0
開始處理.
大家好,我叫張三,今年20歲
結束時間:2018-11-8 17:21:54
Process finished with exit code 0
複製程式碼
注意
Timer
測試不能用單元測試