java多线程的实现方式

2021-04-21  本文已影响0人  analanxingde

1:继承Thread并重写run方法,并调用start方法

/**
 * Java实现多线程
 * 继承Thread类,重写run方法
 */
class MyThread extends Thread {
    @Override
    public void run() {
        //此处为thread执行的任务内容
        System.out.println(Thread.currentThread().getName());
    }
}
public class Demo01 {
    public static void main(String[] args) {
            Thread t = new MyThread();
    }
}

2:实现Runnable接口,并用其初始化Thread,然后创建Thread实例,并调用start方法

/**
 * Java实现多线程的方式2
 * 实现Runnable接口
 */
class MyThread implements Runnable {
    
    @Override
    public void run() {
        //此处为thread执行的任务内容
        System.out.println(Thread.currentThread().getName());
    }
}

public class Demo02 {
    
    public static void main(String[] args) {
            Thread t = new Thread(new MyThread());
            t.start();
        }
    }
}

3:实现Callable接口,并用其初始化Thread,然后创建Thread实例,并调用start方法


/**
 * Java实现多线程的方式3
 * 实现Callable接口
 */
class MyThread implements Callable<Integer> {
    
    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName());
        return null;
    }
}

public class Demo03 {
    
    
    public static void main(String[] args) {
            //创建MyThread实例
            Callable<Integer> c = new MyThread();
            //获取FutureTask
            FutureTask<Integer> ft = new FutureTask<Integer>(c);
            //使用FutureTask初始化Thread
            Thread t = new Thread(ft);
            t.start();
        }
    }
}

4:使用线程池创建


/**
 * Java实现多线程的方式4
 * 线程池
 */
class MyThread implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
    
}

class MyThread2 implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName());
        return 0;
    }

    
}

public class Demo04 {
    
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
            executorService.execute(new MyThread());
            FutureTask<Integer> ft = new FutureTask<Integer>(new MyThread2());
            executorService.submit(ft);
        }
        executorService.shutdown();
    }
}

上一篇 下一篇

猜你喜欢

热点阅读