既然学习多线程,那你就要知道线程是如何创建的,线程又是如何启动的,下面就看一下,线程的创建和启动;
1、创建线程的方法一般有三种:
- 继承Thread类
- 实现Runnable接口
- 实现Callable接口
2、启动线程的方法一般有四种:
- new T01().start();
- new Thread(new T02()).start();
- FutureTask+Callable
- Executors.newCachedThreadPool();
话不多说直接上代码:
package com.example.demo.threaddemo.howtocreatethread; import java.util.concurrent.*; public class How_to_create_thread { //第一种:继承Thread 类 public static class T01 extends Thread{ @Override public void run() { for (int i = 0; i <10; i++) { try { TimeUnit.MICROSECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("extends thread ----------------"); } } } //第二种: 实现Runnable接口 public static class T02 implements Runnable{ @Override public void run() { for (int i = 0; i < 10; i++) { try { TimeUnit.MICROSECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("implements runnable -----------------"); } } } //第三种: 实现Callable接口 public static class T03 implements Callable{ @Override public String call() throws Exception { for (int i = 0; i < 10; i++) { try { TimeUnit.MICROSECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("implements Callable ------------------"); } return "success"; } }
//线程启动测试类 public static void main(String[] args) { //一般线程的启动方法 new T01().start(); new Thread(new T02()).start(); new Thread(new FutureTask<String>(new T03())).start(); //使用lamada表达式启动线程 new Thread(()->{ System.out.println("lamada -------------------------"); }).start(); //线程池的方式 ExecutorService service = Executors.newCachedThreadPool(); service.execute(()->{ System.out.println("Thread pool --------------------"); }); service.shutdown(); } }