1 继承Thread
2 实现Runnable借口
3 实现Callable(优势:可声明异常,可返回值)
package com.lzs.utils;import java.util.concurrent.*;/** * Created by zaish on 2016-3-19. * Callable构建线程(优势:可声明异常,可返回值) */public class Call { public static void main(String[] args) throws ExecutionException, InterruptedException { //创建线程 ExecutorService service= Executors.newFixedThreadPool(2); Race tortaise=new Race("乌龟",1000); Race rabbit=new Race("兔子",500); //获取返回值 Futureresult1=service.submit(tortaise); Future result2=service.submit(rabbit); Thread.sleep(2000); tortaise.setFlag(false);//停止线程体循环 rabbit.setFlag(false); int num1=result1.get(); int num2=result2.get(); service.shutdown(); System.out.println(tortaise.getName()+"跑了-->"+tortaise.getStep()); System.out.println(rabbit.getName()+"跑了-->"+rabbit.getStep()); }}class Race implements Callable{ private String name; private long time; private int step=0; private boolean flag=true; public Race(){ } public Race(String name){ super(); this.name=name; } public Race(String name,long time){ super(); this.time=time; } @Override public Object call() throws Exception { while (flag){ Thread.sleep(time); step++; } return step; } public String getName() { return name; } public long getTime() { return time; } public int getStep() { return step; } public boolean isFlag() { return flag; } public void setName(String name) { this.name = name; } public void setTime(long time) { this.time = time; } public void setStep(int step) { this.step = step; } public void setFlag(boolean flag) { this.flag = flag; }}
4 其他