码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-05-07 22:55:39      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:res   inter   util   ace   调用   override   参数化   接口   string   

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

 

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

标签:res   inter   util   ace   调用   override   参数化   接口   string   

原文地址:https://www.cnblogs.com/teiba/p/9005123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!