继承Thread类
Thread类实际上是Runnable接口的一个实例,代表一个线程的实例。start()方法是一个Native方法。
public class cycThread extends Thread{ public void run(){ System.out.printIn("cycThread.run()"); } } cycYhread cyc = new cycThread(); cyc.start();
实现Runnable接口
若该类应该继承其他类,则可以使用实现Runnable接口。
public class cycRunnable extends OtherClass implements Runnable{ public void run(){ System.out.println("cycThread.run())"); } } cycRunnable cRunnable = new cycRunnable(); Thread thread = new Thread(cRunnable); thread.start();
使用ExecutorService、Callable<class>、Futuer有返回值线程
有返回值的任务必须实现Callable接口,无返回值实现的是Runnable接口。执行Callable任务后,可以获取一个Futter的对象,在该对象上调用get就可以获取到Callback任务返回Object,结合线程池接口ExecutorService就可以实现有返回结果的多线程。
public class Test { public static void main(String[] args) throws ExecutionException, InterruptedException { //创建一个线程池 ExecutorService pool = Executors.newFixedThreadPool(2); //创建多个有返回值的任务 List<Future> list = new ArrayList<Future>(); for (int i =0;i<2;i++){ Callable c = new MyCallable(); //执行任务并获取Future对象 Future f = pool.submit(c); list.add(f); } //关闭线程池 pool.shutdown(); //获取所有不并发任务的运行结果 for (Future f : list){ System.out.println("res:"+f.get().toString()); } } } import java.util.concurrent.Callable; public class MyCallable implements Callable { @Override public Object call() throws Exception { System.out.println("cyc"); return "ok"; } }
执行结果图1
执行效果图2
基于线程池方式
使用缓存策略缓存线程连接数据库的资源,从而做到不用每次连接就去创建线程。
import com.sun.org.apache.xpath.internal.functions.FuncTrue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; public class Test { public static void main(String[] args) throws ExecutionException, InterruptedException { //创建一个线程池 ExecutorService pool = Executors.newFixedThreadPool(10); while (true){ pool.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+":正在执行!"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } }); } } }
执行效果
网友评论