JAVA线程、线程池的创建

一、Java创建线程的三种方式:

1.继承Thread类创建线程类

public class Test1 {
    public static void main(String[] args) {
        MyThread01 t1=new MyThread01();
        MyThread01 t2=new MyThread01();
        t1.start();
        t2.start();
    }
}

class MyThread01 extends Thread{

    @Override
    public void run() {
        System.out.println("线程名:"+currentThread().getName());
    }
}

运行结果

2.实现Runnable接口

public class Demo2 {

    public static void main(String[] args) {

        MyThread02 target=new MyThread02();

        Thread t1=new Thread(target);
        Thread t2=new Thread(target);

        t1.start();
        t2.start();
    }
}

class MyThread02 implements Runnable{

    @Override
    public void run() {
        System.out.println("线程名:"+Thread.currentThread().getName());
    }
}

运行结果

3.通过Callable和Future创建线程

import java.util.concurrent.*;

public class Demo3 {

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        Callable callable=new MyThread03();
        FutureTask task1=new FutureTask(callable);
        FutureTask task2=new FutureTask(callable);
        new Thread(task1).start();
        new Thread(task2).start();
        Thread.sleep(10);//等待线程执行结束

        //task.get() 获取call()的返回值。若调用时call()方法未返回,则阻塞线程等待返回值
        System.out.println(task1.get());
        System.out.println(task2.get());

        //get的传入参数为等待时间,超时抛出超时异常;传入参数为空时,则不设超时,一直等待
        System.out.println(task1.get(10L, TimeUnit.MILLISECONDS));
        System.out.println(task2.get(10L, TimeUnit.MILLISECONDS));
    }
}

class MyThread03 implements Callable{

    @Override
    public Object call() throws Exception {
        System.out.println("线程名:"+Thread.currentThread().getName());
        return "实现callable:"+Thread.currentThread().getName();
    }
}

运行结果

二、创建线程的三种方式的对比

1、采用实现Runnable、Callable接口的方式创建多线程

优势:

线程类只是实现了Runnable接口或Callable接口,还可以继承其他类。

在这种方式下,多个线程可以共享同一个target对象,所以非常适合多个相同线程来处理同一份资源的情况,从而可以将CPU、代码和数据分开,形成清晰的模型,较好地体现了面向对象的思想。

劣势:

编程稍微复杂,如果要访问当前线程,则必须使用Thread.currentThread()方法

2、使用继承Thread类的方式创建多线程

优势:

编写简单,如果需要访问当前线程,则无需使用Thread.currentThread()方法,直接使用this即可获得当前线程

劣势:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值