1.繼承Thread,重寫run()
public class MyThread extends Thread{
@Override
public void run() { System.out.println("運行過程"); } }
2.實現Runnable,重run()
public class MyRunnable implements Runnable {
@Override
public void run() { System.out.println("運行過程"); } }
3.實現Callable,重寫call()
注意:Callable接口是一個參數化的類型,只有一個call方法,call返回類型是參數類型。
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/ V call() throws Exception; }
import java.util.concurrent.Callable;
public class MyCallale implements Callable<Integer> { @Override public Integer call() throws Exception { System.out.println("運行過程"); return null; } }
面試題:有線程A、B、C,A、B同時執行,A、B執行完畢之后,執行C
分析:考同步運行和異步運行,A、B異步,AB和C同步(AB阻塞,執行完成后才能執行C)
代碼:(實現Callable,利用FutureTask創建A、B線程,調用get()方法阻塞A、B線程,最后啟動線程C)
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class CallableTest { public static void main(String[] args) throws InterruptedException, ExecutionException { //線程A、B同時運行,線程C在A、B之后運行 Callable<A> a = new Callable<A>(){ @Override public A call() throws Exception { for(int i = 0; i < 10; i++){ System.out.print(" A" + i); } return new A(); } }; Callable<B> b = new Callable<B>(){ @Override public B call() throws Exception { for(int i = 0; i < 10; i++){ System.out.print(" B" + i); } return new B(); } }; FutureTask<A> taskA = new FutureTask<A>(a); FutureTask<B> taskB = new FutureTask<B>(b); new Thread(taskA).start(); new Thread(taskB).start(); if(taskA.get() != null && taskB.get() != null){ new Thread(new C()).start(); } } static class A{} static class B{} static class C extends Thread{ @Override public void run() { for(int i = 0; i < 10; i++){ System.out.print(" C" + i); } } } }