四种线程写法

第一种:继承Thread类

public class ThreadOne extends Thread {

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("输出"+i);
        }
    }
}

class TestOne{
    public static void main(String[] args) {
        ThreadOne one = new ThreadOne();
        one.start();
    }
}

第二种:实现Runnable接口

public class ThreadTwo implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("输出"+i);
        }
    }
}

class TestTwo{
    public static void main(String[] args) {
        ThreadTwo two = new ThreadTwo();
        Thread thread = new Thread(two);
        thread.start();
    }
}

第三种:实现Callable接口

public class ThreadThree implements Callable<Object> {

    @Override
    public Object  call() throws Exception {
        int value = 0;
        for (int i = 1; i < 10; i++) {
            value += i;
        }
        return value;
    }
}

class TestThree{
    public static void main(String[] args) {
        ThreadThree threadThree = new ThreadThree();
        FutureTask futureTask = new FutureTask(threadThree);
        Thread thread = new Thread(futureTask);
        thread.start();
        try{
            Object value = futureTask.get();
            System.out.println("值为"+value);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

第四种:使用线程池

public class ThreadFour {
    public static void main(String[] args) {
        //ExecutorService threadPool = Executors.newSingleThreadExecutor(); //创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
        //ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(10);//创建一个定长线程池,支持定时及周期性任务执行。
        //ExecutorService threadPool = Executors.newFixedThreadPool(10); //创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
        ExecutorService threadPool = Executors.newCachedThreadPool(); //创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
        try {
            for (int i = 0; i < 10; i++) {
                //使用线程池来创建线程
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"输出");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown(); //线程池使用完毕后需要关闭
        }
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值