join()
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
ThreadCase t = new ThreadCase();
t.start();
System.out.println("start...");
long before = System.currentTimeMillis();
t.join();
long after = System.currentTimeMillis();
System.out.println("total is: " + t.count + " cost: " + (after-before) + " ms");
}
static class ThreadCase extends Thread{
int count;
public void run() {
for(int i=0; i<10; i++) {
count += i;
}
System.out.println("caculate completely.");
}
}
wait(), notify
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
ThreadCase t = new ThreadCase();
t.start();
long before = System.currentTimeMillis();
synchronized(t) {
System.out.println("start...");
t.wait();
}
long after = System.currentTimeMillis();
System.out.println("total is: " + t.count + " cost: " + (after-before) + " ms");
}
static class ThreadCase extends Thread{
int count;
public void run() {
synchronized(this) {
for(int i=0; i<10; i++) {
count += i;
}
System.out.println("caculate completely.");
notify();
}
}
}
callable
public static void main(String[] args) throws InterruptedException, ExecutionException {
// TODO Auto-generated method stub
CallableCase c = new CallableCase();
FutureTask<Integer> task = new FutureTask<>(c);
new Thread(task).start();
long before = System.currentTimeMillis();
System.out.println("waiting for calculating...");
Integer result = task.get();
long after = System.currentTimeMillis();
System.out.println("total is: " + result + " cost: " + (after-before) + " ms");
}
static class CallableCase implements java.util.concurrent.Callable<Integer> {
int count = 0;
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
for(int i=0; i<10; i++) {
count += i;
}
System.out.println("calculate completely");
return Integer.valueOf(count);
}
}
Callable 与 Runnable
callable可以直接返回处理结果或抛出异常,runnable自己消化异常
callable,调用FutureTask.get()来获取返回结果,此时会阻塞主线程来获取“将来”的结果,否则不会阻塞