Java创建线程的四种方式

1.继承Thread类实现多线程

    run()为线程类的核心方法,相当于主线程的main方法,是每个线程的入口
    a.一个线程调用多次start()方法将会抛出线程状态异常,也就是的start()只可以被调用一次 
    b.native生明的方法只有方法名,没有方法体。是本地方法,不是抽象方法,而是调用c语言方法
      registerNative()方法包含了所有与线程相关的操作系统方法
    c. run()方法是由jvm创建完本地操作系统级线程后回调的方法,不可以手动调用(否则就是普通方法)

public class MyThread extends Thread {

  public MyThread() {

  }

  public void run() {

    for(int i=0;i<10;i++) {

    System.out.println(Thread.currentThread()+":"+i);

  }

}

  public static void main(String[] args) {

    MyThread mThread1=new MyThread();

    MyThread mThread2=new MyThread();

    MyThread myThread3=new MyThread();

    mThread1.start();

    mThread2.start();

    myThread3.start();

  }

}

2.覆写Runnable()接口实现多线程,而后同样覆写run().推荐此方式

    a.覆写Runnable接口实现多线程可以避免单继承局限
    b.当子类实现Runnable接口,此时子类和Thread的代理模式(子类负责真是业务的操作,thread负责资源调度与线程创建辅助真实业务。
public class MyThread implements Runnable{
    public static int count=20;
    public void run() {
        while(count>0) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"-当前剩余票数:"+count--);
        }
    }
    public static void main(String[] args) {
        MyThread Thread1=new MyThread();
        Thread mThread1=new Thread(Thread1,"线程1");
        Thread mThread2=new Thread(Thread1,"线程2");
        Thread mThread3=new Thread(Thread1,"线程3");
        mThread1.start();
        mThread2.start();
        myThread3.start();
    }
}

继承Thread和实现Runnable接口的区别

    a.实现Runnable接口避免多继承局限
    b.实现Runnable()可以更好的体现共享的概念

3.使用Callable和Future接口实现多线程

从继承Thread类和实现Runnable接口可以看出,上述两种方法都不能有返回值,且不能声明抛出异常。而Callable接口则实现了此两点,Callable接口如同Runable接口的升级版,其提供的call()方法将作为线程的执行体,同时允许有返回值。

  但是Callable对象不能直接作为Thread对象的target,因为Callable接口是 Java 5 新增的接口,不是Runnable接口的子接口。对于这个问题的解决方案,就引入 Future接口,此接口可以接受call() 的返回值,RunnableFuture接口是Future接口和Runnable接口的子接口,可以作为Thread对象的target 。并且Future 接口提供了一个实现类:FutureTask 。

  FutureTask实现了RunnableFuture接口,可以作为 Thread对象的target。

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
 
public class MyThread implements Callable<String> {
    private int count = 20;
 
    @Override
    public String call() throws Exception {
        for (int i = count; i > 0; i--) {
//            Thread.yield();
            System.out.println(Thread.currentThread().getName()+"当前票数:" + i);
        }
        return "sale out";
    } 
 
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Callable<String> callable  =new MyThread();
        FutureTask <String>futureTask=new FutureTask<>(callable);
        Thread mThread=new Thread(futureTask);
        Thread mThread2=new Thread(futureTask);
        Thread mThread3=new Thread(futureTask);
//        mThread.setName("hhh");
        mThread.start();
        mThread2.start();
        mThread3.start();
        System.out.println(futureTask.get());
        
    }
}

4.通过线程池启动多线程

通过Executor 的工具类可以创建三种类型的普通线程池:

FixThreadPool(int n); 固定大小的线程池

 使用于为了满足资源管理需求而需要限制当前线程数量的场合。使用于负载比较重的服务器。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class Test {
    public static void main(String[] args) {
        ExecutorService ex=Executors.newFixedThreadPool(5);
        
        for(int i=0;i<5;i++) {
            ex.submit(new Runnable() {
                
                @Override
                public void run() {
                    for(int j=0;j<10;j++) {
                        System.out.println(Thread.currentThread().getName()+j);
                    }
                    
                }
            });
        }
        ex.shutdown();
    }    
}

SingleThreadPoolExecutor :单线程池

需要保证顺序执行各个任务的场景 

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class Test {
    public static void main(String[] args) {
        ExecutorService ex=Executors.newSingleThreadExecutor();
        
        for(int i=0;i<5;i++) {
            ex.submit(new Runnable() {
                
                @Override
                public void run() {
                    for(int j=0;j<10;j++) {
                        System.out.println(Thread.currentThread().getName()+j);
                    }
                    
                }
            });
        }
        ex.shutdown();
    }    
}

CashedThreadPool(); 缓存线程池

当提交任务速度高于线程池中任务处理速度时,缓存线程池会不断的创建线程
 适用于提交短期的异步小程序,以及负载较轻的服务器

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class Test {
    public static void main(String[] args) {
        ExecutorService ex=Executors.newCachedThreadPool();
        
        for(int i=0;i<5;i++) {
            ex.submit(new Runnable() {
                
                @Override
                public void run() {
                    for(int j=0;j<10;j++) {
                        System.out.println(Thread.currentThread().getName()+j);
                    }
                    
                }
            });
        }
        ex.shutdown();
    }    
}

线程之间的状态,及他们之间的相互转换

Java创建线程的四种方式