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

java线程启动的三种方式

时间:2020-06-14 12:28:40      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:ash   san   policy   exception   start   htm   size   eve   java   

java线程启动的三种方式

原生的Thread,Runable和借助concurent包中的Callable与FutureTask,实现有返回值的线程

import org.omg.PortableServer.THREAD_POLICY_ID;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 实现Thread的几种方法
 */
public class ThreadTest{
    public static void main (String[] args) throws Exception {
        thread t = new thread("thread");
        t.start();


        Thread r = new Thread(new runnableThread(), "runnable");
        r.start();


        FutureTask<Integer> task = new FutureTask<>(new callable());
        Thread c = new Thread(task, "callable");
        c.start();
        System.out.println("返回值" + task.get());
    }
}

class thread extends Thread{
    public thread(String name){
        super(name);
    }

    @Override
    public void run() {
        System.out.println(currentThread().getName() + "启动了");
        System.out.println("------------------------------------");

    }
}

class runnableThread implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "启动了");
        System.out.println("------------------------------------");
    }
}

class callable implements Callable<Integer>{
    private int i = 1;

    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName() + "启动了");
        return i;
    }
}


java线程启动的三种方式

标签:ash   san   policy   exception   start   htm   size   eve   java   

原文地址:https://www.cnblogs.com/muche-moqi/p/13124151.html

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