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);
- }
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2591470.html