本文共 1764 字,大约阅读时间需要 5 分钟。
实现多线程有3种方法:继承Thread类、实现Runnable接口、实现Callable接口(第三种变化可以参考http://blog.csdn.net/aboy123/article/details/38307539)
一、继承Thread类
public class TestThread extends Thread{
public void run(){
System.out.print(“启动线程”);
}
public static void main(String args[]){
Thread th=new Thread();
th.start();
}
}
二、实现Runnable接口
public class TestRunnable implements Runnable{
public void run(){
System.out.print(“启动线程”);
}
public static void main(String args[]){
TestRunnable tb=new TestRunnable();
Thread th=new Thread(tb);
th.run();
}
}
三、实现Callable接口
package test.querySystem.util;
import java.util.ArrayList; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future;//不能在public 类中实现Callable接口class TestResultThread implements Callable<String>{ private int id;//有参数构造方法public TestResultThread(int id){ this.id=id;}@Overridepublic String call() throws Exception { return “线程任务返回值”+id;}} public class TestThreadCallnable { public static void main(String args[]) throws InterruptedException, ExecutionException{ //创建线程池ExecutorService exec=Executors.newCachedThreadPool();//创建线程容器ArrayList<Future<String>> result=new ArrayList<Future<String>>();//执行任务后返回结果,假如只有10个线程for(int i=0;i<10;i++){ Future<String> f=exec.submit(new TestResultThread(i));result.add(f);}//遍历执行完成后的线程for(Future<String> ft:result){ //判断是否执行完成if(ft.isDone()){ System.out.println(“完成的线程:”+ft.get());}else{ System.out.println(“未完成的线程:”+ft);}}//关闭线程池exec.shutdown();} }注意:1、如果不需要返回值,最好使用Runnable接口
2、如果Executor后台线程池还没有完成,那么这调用返回Future对象的get()方法,会阻塞直到计算完成。
3、Callable规定Call()方法,而Runnable规定run()方法
4、杀死进程最好就在类里面调用destroy()方法;不要实例化后再杀死!因为不知道线程到底什么时候结束!
转载地址:https://blog.csdn.net/jinpengncu/article/details/79641367 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!