Java多线程:创建多线程的三种方式

在Java中,有三种方式创建多线程,继承类Thread,继承接口Runnable,继承接口Callable。其中Thread和Runnable需要重写方法run,方法run没有返回值;Callable需要重写方法call,方法call可以返回值。

Thread实现如下:

package ch01;


/**
 * @copyright 2003-2024
 * @author    qiao wei
 * @date      2024-01-04 15:47
 * @version   1.0
 * @brief     
 * @history   
 */
public class MyThread extends Thread {

    @Override
    public void run() {
        super.run();
    
        for (int index = 0; 100 != index; ++ index) {
            System.out.println("----------子线程:" + index + ", " + Thread.currentThread().threadId());
        }
    }
}

Runnable实现如下:

package ch01;


/**
 * @copyright 2003-2024
 * @author    qiao wei
 * @date      2024-01-04 15:58
 * @version   1.0
 * @brief     
 * @history   
 */
public class MyRunnable implements Runnable {
    
    public MyRunnable() {}

    @Override
    public void run() {
        for (int index = 0; 100 != index; ++ index) {
            System.out.println("----------子线程:" + index + ", " + Thread.currentThread().threadId());
        }
    }
}

Callable实现如下:

package ch01;


import java.util.concurrent.Callable;

/**
 * @copyright 2003-2024
 * @author    qiao wei
 * @date      2024-01-04 16:21
 * @version   1.0
 * @brief     继承接口Callable进行多线程。
 * @history   
 */
public class MyCallable implements Callable<String> {

    public MyCallable(int count) {
        this.count = count;
    }

    /**
     * @author  qiao wei
     * @brief   通过程序处理,返回响应值。
     * @param   
     * @return  返回处理后的Integer数据。
     * @throws  
     */
    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int index = 0; index != count; ++index) {
            sum += index;
        }
        // 有返回值。
        return Integer.toString(sum);
    }
    
    private int count;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值