JAVA中创建线程的三种方式

2021/5/16 1:26:57

本文主要是介绍JAVA中创建线程的三种方式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

JAVA中创建线程的三种方式

1 继承Thread类

重写run方法,使用start()开启线程,如此,就可以同时做多件事情

public class MyThread extends Thread{

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread()+ " " + i);
        }
    }
}

public class Main {

    public static void main(String[] args) {
        MyThread mt = new MyThread();
        mt.start();

        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread()+ " " + i);
        }
    }
}

2 实现Runnable接口

因为java是单继承机制,所以实现接口的方式更常使用。同样需要重写run方法,使用start()开启线程

public class MyThread2 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread()+ " " + i);
        }
    }
}

public class Main {

    public static void main(String[] args) {

        MyThread2 mt = new MyThread2();
        Thread t = new Thread(mt);
        t.start();

        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread()+ " " + i);
        }
    }
}

3 实现Callable接口

通过此种方式开启的线程,可以存在返回值,主线程可以等待此线程执行完毕之后继续执行,也可以选择兵分两路
重写call()方法

public class MyThread3 implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {

        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum+=i;
        }
        return sum;
    }
}

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Main {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        Callable<Integer> callable = new MyThread3();
        FutureTask<Integer> task = new FutureTask<>(callable);

        new Thread(task).start();
        Integer integer = task.get();
        System.out.println(integer);//输出4590
    }
}


这篇关于JAVA中创建线程的三种方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程