java多线程系列1-初识多线程多线程4种实现方式
1、继承Thread
2、实现Runnable接口
3、实现Callable<V>接口
4、线程池
太基础了直接上代码
import java.util.concurrent.*; public class Test { public static void main(String[] args) throws ExecutionException, InterruptedException { /** * 继承Thread 重写run方法,实际上这个run就是 Thread类成员变量Runnable的run方法 */ for(int i = 0 ; i < 20; i ++){ MyThread myThread = new MyThread(); /** * java是不直接与硬件打交道的,所以不会直接控制线程,线程的创建和启动是由本地方法完成。Thread通过调用本地方法start0来创建启动线程 */ myThread.start(); } /** * 实现Runnable结构,然后使用Thread(Runnable target)构造方法 */ for(int i = 0 ; i < 20; i ++){ Thread thread = new Thread(new MyRunnable()); thread.start(); } /** * 带返回值的线程,实际上还是Thread实现的,只是在原来的基础上增加了阻塞,等到线程结束后获得线程返回值 * 1、实现Callable接口,重写call方法 * 2、FutureTask(Callable<V> callable) 创建FutureTask实例 * 3、使用Thread(Runnable target)构造方法创建Thread实例,调用Thread实例start方法启动线程。FutureTask是Runnable的子类 * 4、调用FutureTask.get方法获得返回值 */ for(int i = 0 ; i < 20; i ++){ Callable<String> myCallable = new MyCallable(); FutureTask<Callable<String>> futureTask = new FutureTask(myCallable); Thread thread = new Thread(futureTask); thread.start(); System.out.println("callable main :" + thread.getId() + ", call:" + futureTask.get()); } /** * 使用线程池的方式 * 1、Executors.newFixedThreadPool创建固定大小的线程池 * 2、创建Runnable,或者Callable对象 * 3、调用executorService.submit调用线程 * */ ExecutorService executorService = Executors.newFixedThreadPool(5); for(int i = 0 ; i < 20; i ++){ Future<String> submit = executorService.submit(new Callable<String>() { @Override public String call() throws Exception { return "pool callable :" + Thread.currentThread().getId(); } }); System.out.println(submit.get()); } } static class MyCallable implements Callable<String> { @Override public String call() throws Exception { System.out.println("mycallable run: " + Thread.currentThread().getId() ); return "callable"; } } static class MyRunnable implements Runnable { @Override public void run() { System.out.println("runnable run :" + Thread.currentThread().getId()); } } static class MyThread extends Thread { @Override public void run() { System.out.println("thread run:" + this.getId()); } } }