1.继承Thread类来实现线程
/*** 实现方式一,继承Thread类,覆写run方法*/public class MyThread extends Thread{@Overridepublic void run() {for (int i = 0; i < 10; i++) {System.out.println("ThreadName:" + Thread.currentThread().getName() + ":" + i);}}}
这就是继承Thread的类来实现线程,我们可以看一下run方法的源码
public void run() {if (target != null) {target.run();}}
这里说明了Thread类中的run方法如果target不为null,那么就调用target.run(),否则什么也不处理,而target的类型其实是Runnable,当线程实例是通过构造器Thread(Runnable target)创建的,那么target的值就是构造器中的值,否则target为null
2.实现Runnable接口来现实线程
/*** 实现方式二,实现Runnable接口,覆写run方法*/public class MyRunnable implements Runnable{@Overridepublic void run() {for (int i = 0; i < 10; i++) {System.out.println("ThreadName:" + Thread.currentThread().getName() + ":" + i);}}}
3.使用匿名内部类实现线程
/*** 匿名内部类*/public static void anonymousThread() {new Thread() {//直接实现run方法@Overridepublic void run() {for (int i = 0; i < 10; i++) {System.out.println("ThreadName:" + Thread.currentThread().getName() + ":" + i);}}}.start();}
4.实现Callable接口来实现线程
/*** 实现了Callable接口,覆写Callable中的call方法*/public class MyCallThread implements Callable<Integer> {@Overridepublic Integer call() throws Exception {int sum = 0;for (int i = 0; i < 10; i++) {sum += i;}return sum;}}
5.实现用线程池来实现线程
严格的来说,这种方式的区别其实和直接实现Runnable接口区别不大,但是这里使用了线程池的方式
/*** 用线程池的方式来实现线程*/public class ThreadPool implements Runnable{@Overridepublic void run() {for (int i = 0; i < 10; i++) {System.out.println("ThreadName:" + Thread.currentThread().getName() + ":" + i);}}}public static void ThreadPoolStart() {//创建一个容量大小为5的线程池ExecutorService pool = Executors.newFixedThreadPool(6);ThreadPoolExecutor executor = (ThreadPoolExecutor)pool;executor.setCorePoolSize(5);//开启线程executor.execute(new ThreadPool());executor.execute(new ThreadPool());executor.execute(new ThreadPool());executor.execute(new ThreadPool());executor.execute(new ThreadPool());}
6.Lambda实现线程1
/*** 普通线程,无返回值*/public static void Thread1() {//这里面的代码就是run方法区域new Thread(() -> {for (int i = 0; i < 10; i++) {System.out.println("ThreadName:" + Thread.currentThread().getName() + ":" + i);}}).start();}
7.Lambda实现线程2
/*** 使用线程池实现异步线程*/public static void Thread2() {ExecutorService pool = Executors.newFixedThreadPool(5);pool.submit(() -> {for (int i = 0; i < 10; i++) {System.out.println("ThreadName:" + Thread.currentThread().getName() + ":" + i);}});}
8.Lambda实现线程3
/*** 使用线程池实现异步线程,可以返回参数*/public static String Thread3() {ExecutorService pool = Executors.newFixedThreadPool(5);Future<String> result = (Future<String>) pool.submit(() -> {for (int i = 0; i < 10; i++) {System.out.println("ThreadName:" + Thread.currentThread().getName() + ":" + i);}});try {return result.get();} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}return null;}}
