创建线程的方式
创建线程的方式
一个java应用程序,java.exe中至少包含了三个线程:
main()线程、gc线程、异常处理线程
继承Thread 类
重写Thread的run()方法,通过start启动多线程。
说明
如果我们自己手动调用run()方法,那就是普通方法,没有启动多线程,要想启动多线程就得调用start方法,一个线程对象只能调用一次run方法,多次调用会报异常。
实现Runnable接口
- 也是实现 run()方法,然后thread通过start启动多线程
- 不同就是需要将实现了Runnable 接口的实现类传到Thread()构造器中,然后Thread类对象调用start启动多线程。
实现callable接口
- 实现call方法
- 创建Callable 接口的实现类对象,
- 将此对象作为参数传递到FutureTask构造器中,创建出FutureTask对象
- 将FutureTask对象作为参数传递到Thread()构造器中,创建了Thread类对象调用start方法
- 获取Callable中call方法的返回值
public class CallableTest { public static void main(String[] args) { StringThread stringThread = new StringThread(); FutureTask futureTask = new FutureTask(stringThread); Thread thread = new Thread(futureTask); thread.start(); String s = null; try { s = (String) futureTask.get(); System.out.println(s); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } class StringThread implements Callable{ @Override public String call() throws Exception { System.out.println("call is running"); return "this is callable Thread"; } }
使用线程池创建
使用ThreadPoolExecutor 来创建。
public class ThreadPoolTest { public static void main(String[] args) { ExecutorService executor = new ThreadPoolExecutor(1,2,2, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3)); executor.execute(new ThreadR()); executor.execute(new ThreadR()); executor.shutdown(); } } class ThreadR implements Runnable{ @Override public void run() { System.out.println(123); } }