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 {

    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;
}

你可能感兴趣的:(Java,java,开发语言)