Java多线程实现的3种方式

直接继承Thread类,重写run方法

package snippet;
public class test {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new MyThread().start();
        }
    }
}
class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            System.out.println(getName() + "--->" + i);
        }
    }
}

使用Runable接口+Thread

作为Thread 参数传入(与上面没有什么不同,只是为了减少设计的藕性)

package snippet;
public class test {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(new MyRunnable()).start();
        }
    }
}
class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "--->" + i);
        }
    }
}

注意,当实现Runable接口并且覆写Thread的run方法时,只会调用Thread的run方法.

使用Runable接口

使用Runable接口比较复杂,需要使用到线程池,但是它可以带返回值

package snippet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable {
    
    private int    num1;
    private int    num2;
                
    public MyCallable(int num1, int num2) {
        try {
            this.num1 = num1;
            this.num2 = num2;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public Integer call() throws Exception {
        return num1 + num2;
    }
    
}
public class test {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newCachedThreadPool();
        /**
         * 创建一个线程池
         */
        List> results = new ArrayList<>();
        /**
         * Future是泛型接口,其中泛型为返回数据类型
         */
        
        for (int i = 0; i < 5; i++) {
            Future result = pool.submit(new MyCallable(i, i + 1));
            results.add(result);
        }
        
        for (int i = 0; i < results.size(); i++) {
            System.out.println(results.get(i).get());
        }
        /**
         * 使用get去获取call方法返回的值,可设置超时. 因为有时候若等待时间太长,则造成体验不好
         */
    }
}

你可能感兴趣的:(Java多线程实现的3种方式)