创建线程的五种方式

Runnable

public class ThreadPool implements Runnable {

    private int i;

    public ThreadPool() {}
    public ThreadPool(int i) {
        this.i = i;
    }

    @Override
    public void run() {
        System.out.println("***************start run**************" + i);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("***************end run****************" + i + " " + this.toString());
    }
}

Thread

public class ThreadExtend extends Thread {

    @Override
    public void run() {
        System.out.println("---------" + getName() + "----------");
    }
}

Lambda

Thread thread = new Thread(() -> System.out.println("------- runnable -------"));

Callable

public class ThreadCallable implements Callable<String> {
    @Override
    public String call() {
        String threadName = Thread.currentThread().getName();
        System.out.println("---------" + threadName + "----------");
        return threadName;
    }

    public static void main(String[] args) {
        ThreadCallable callable = new ThreadCallable();
        FutureTask<String> futureTask = new FutureTask<>(callable);
        Thread thread = new Thread(futureTask);
        try {
            thread.start();
            System.out.println(futureTask.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

Executors

import haut.zm.thread.factory.MyThreadFactory;
import haut.zm.thread.implement.ThreadPool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zm
 * @date 2020/09/12
 */
public class ThreadExecutorsMain {

    /**
     * 单例线程,可以保证所有的任务按照指定的顺序执行(FIFO, LIFO, 优先级)
     */
    private static ExecutorService executorSingle = Executors.newSingleThreadExecutor();

    /**
     * 核心线程数、最大线程数、维持时间、时间类型、工作队列、线程池工厂
     */
    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 20, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new MyThreadFactory("test"));

    /**
     * 指定线程数,超出线程数量的线程会在队列中进行等待
     */
    private static ExecutorService executorFixed = Executors.newFixedThreadPool(2);

    /**
     * 不定线程数,最大线程数为Integer.MAX_VALUE
     */
    private static ExecutorService executorCached = Executors.newCachedThreadPool();

    /**
     * 定长线程池,创建一个定长线程池,支持定时及周期性任务执行。
     */
    private static ExecutorService executorScheduled = Executors.newScheduledThreadPool(2);

    /**
     * @param args run()和start()的区别可以用一句话概括:单独调用run()方法,是同步执行;通过start()调用run(),是异步执行。
     *             <p>
     *             线程sleep 和wait 的区别:
     *             1、这两个方bai法来自不du同的类分别是Thread和Object
     *             2、最主要zhi是sleep方法没有释放锁,而wait方法释放了锁,使得dao其他线程可以使用同步控制块或者方法。
     *             3、wait,notify和notifyAll只能在同步控制方法或者同步控制块里面使用,而sleep可以在任何地方使用(使用范围)
     *             4、sleep必须捕获异常,而wait,notify和notifyAll不需要捕获异常
     *             5、sleep是Thread类的静态方法。sleep的作用是让线程休眠制定的时间,在时间到达时恢复,也就是说sleep将在接到时间到达事件事恢复线程执行。wait是Object的方法,也就是说可以对任意一个对象调用wait方法,调用wait方法将会将调用者的线程挂起,直到其他线程调用同一个对象的notify方法才会重新激活调用者。
     */
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 4; i++) {
            executorFixed.execute(new ThreadPool(i));
        }

        Thread.sleep(10000);

        for (int i = 0; i < 4; i++) {
            executorCached.execute(new ThreadPool(i));
        }

        Thread.sleep(10000);

        for (int i = 0; i < 4; i++) {
            executorSingle.execute(new ThreadPool(i));
        }

        Thread.sleep(10000);

        for (int i = 0; i < 4; i++) {
            executorScheduled.execute(new ThreadPool(i));
        }

        Thread.sleep(10000);

        for (int i = 0; i < 4; i++) {
            threadPoolExecutor.execute(new ThreadPool(i));
        }

        while (true) {
            AtomicInteger i = new AtomicInteger(0);
            executorCached.submit(i::getAndIncrement);
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值