teiba

导航

java创建线程的几种方式,了解一下

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);
            }
        }
    }
}

 

posted on 2018-05-07 21:36  teiba  阅读(1481)  评论(0编辑  收藏  举报