线程创建的几种方式

Java中线程创建主要有以下几种方式

继承Thread类 、实现Runnable接口、实现Callable接口、线程池创建

具体信息如下:

1、继承Thread类

public class ThreadTest1 extends Thread{ @Override public void run() { System.out.println(Thread.currentThread().getName()+" 继承Thread方式创建线程生效了"); } public static void main(String[] args) { ThreadTest1 tt1 = new ThreadTest1(); ThreadTest1 tt2 = new ThreadTest1(); tt1.start(); tt2.start(); }}

2、实现Runnable接口

public class ThreadTest2 implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName()+" 实现Runnable接口创建线程生效了"); } public static void main(String[] args) { ThreadTest2 tt = new ThreadTest2(); ThreadTest2 tt2 = new ThreadTest2(); Thread thread1 = new Thread(tt, "线程1"); Thread thread2 =new Thread(tt2,"线程2"); thread1.start(); thread2.start(); }}

3、实现Callable接口

public class ThreadTest3 implements Callable { @Override public String call() throws Exception { System.out.println(Thread.currentThread().getName()+" 实现Callable接口创建线程生效了"); return Thread.currentThread().getName()+"成功了"; } public static void main(String[] args) throws ExecutionException, InterruptedException { ThreadTest3 threadTest3 = new ThreadTest3(); ThreadTest3 threadTest4 = new ThreadTest3(); FutureTask futureTask1 = new FutureTask<>(threadTest3); FutureTask futureTask2 = new FutureTask<>(threadTest4); Thread thread1 = new Thread(futureTask1,"线程1"); Thread thread2 = new Thread(futureTask2,"线程2"); thread1.start(); thread2.start(); System.out.println(futureTask1.get()); System.out.println(futureTask2.get()); }}

4、通过线程池创建多线程

Executor工具类创建 ,一般使用ThreadPoolExecutor来创建

public class ThreadTest4 { public static void main(String[] args) { // 固定长度线程池 容易OOM 线程最多 Integer.MAX_VALUE ExecutorService fixedThreadPool=Executors.newFixedThreadPool(5); // 缓存线程池 容易OOM 线程最多 Integer.MAX_VALUE ExecutorService cachedThreadPool=Executors.newCachedThreadPool(); // 单个线程池 ExecutorService singleThreadExecutor=Executors.newSingleThreadExecutor(); // 定时线程池 容易OOM 线程最多 Integer.MAX_VALUE ExecutorService scheduledThreadPool= Executors.newScheduledThreadPool(10); fixedThreadPool.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+" 执行了"); } }); fixedThreadPool.shutdown(); cachedThreadPool.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+" 执行了"); } }); cachedThreadPool.shutdown(); singleThreadExecutor.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+" 执行了"); } }); singleThreadExecutor.shutdown(); scheduledThreadPool.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+" 执行了"); } }); scheduledThreadPool.shutdown(); }}

你可能感兴趣的:(线程创建的几种方式)