线程创建的四种方式

方式一: 继承Thread类

public class thread {

    public static void main(String[] args) {
        thread1 thread1=new thread1();
        Thread thread=new Thread(thread1);
        thread.start();
    }
}
class thread1 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i <3 ; i++) {
            System.out.println("thread1:"+currentThread().getName());
        }
    }
}

在这里插入图片描述

方式二: 实现Runnable接口

public class thread {

    public static void main(String[] args) {
        thread2 thread2=new thread2();
        Thread thread=new Thread(thread2);
        thread.start();

    }
}
class thread2 implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i <3 ; i++) {
            System.out.println("thread2:"+Thread.currentThread().getName());
        }
    }
}

在这里插入图片描述

方式三: 实现Callable接口

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class thread {

    public static void main(String[] args) throws Exception {
        thread3 thread3=new thread3();
        FutureTask futureTask=new FutureTask(thread3);
        Thread thread=new Thread(futureTask);
        thread.start();
    }
}
class thread3 implements Callable{

    @Override
    public Object call() throws Exception {
        for (int i = 0; i <3 ; i++) {
            System.out.println("thread3:"+Thread.currentThread().getName());
        }
        return true;
    }
}

在这里插入图片描述

方式四: 线程池

import java.util.concurrent.*;
public class thread {

    public static void main(String[] args) throws Exception {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 2L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        try {
            for (int i = 0; i < 3; i++) {
                threadPoolExecutor.execute(() -> {
                    System.out.println("thread4:" + Thread.currentThread().getName());
                });
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPoolExecutor.shutdown();

        }
    }
}

在这里插入图片描述
线程池的具体原理可以看我的线程池那片文章。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值