java实现多线的几种方式

1.继承Thread类

Thread类实际上实现了Runnable接口,在作用上与实现Runnable接口无异,只是写法的差异。但由于java是单继承的,使用实现Runnable接口的方法也便于多个线程访问同一资源,所以这种继承Thread类的实现方法一般不推荐使用,看看就好

具体代码如下

public class Test2 {
    public static void main(String[] args) {
        MyThread thread = new MyThread("继承Thread类");
        thread.start();
    }
}
public class MyThread extends Thread {
    private String type;

    MyThread(String type) {
        super();
        this.type = type;
    }

    @Override
    public void run() {
        System.out.println("type is:" + type);
    }
}

2.实现Runnable接口

最常用的方法,用就对了

具体代码如下

public class Test2 {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable("实现Runnable接口");
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}
public class MyRunnable implements Runnable {
    private String type;

    MyRunnable(String type) {
        super();
        this.type = type;
    }

    @Override
    public void run() {
        System.out.println("type is:" + type);
    }
}

3.实现Callable接口

Runnable接口的强化版,实现的call()方法可以有返回值,用future.get()方法获取,还可以指定返回值类型,并且可以捕获异常

具体代码如下

public class Test2 {
    public static void main(String[] args) {
        MyCallable myCallable = new MyCallable("实现Callable接口");
        //创建一个只有单个线程的线程池
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future<String> future = threadPool.submit(myCallable);
        try {
            //用get()方法获取线程执行的返回值
            String typeMessage = future.get();
            System.out.println(typeMessage);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
public class MyCallable implements Callable<String> {
    private String type;

    MyCallable(String type) {
        super();
        this.type = type;
    }

    @Override
    public String call() throws Exception {
        return "type is:" + type;
    }
}

有任何问题和见解请留言

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值