实现多线程的方式

继承Thead类

public class ThreadDemo extends Thread{

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

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            ThreadDemo demo = new ThreadDemo();
            demo.start();
        }
    }
}

实现Runnable接口

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

    public static void main(String[] args) {
        RunableThread runableThread = new RunableThread();
        for (int i = 0; i < 100; i++) {
            new Thread(runableThread).start();
        }
    }
}

实现Callable接口有返回值的线程

public class CallableAndFuture implements Callable<String> {

    @Override
    public String call() throws Exception {
        return Thread.currentThread().getName();
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> task = new FutureTask<String>(new CallableAndFuture());
        new Thread(task).start();
        System.out.println(task.get());
    }
}


标题:实现多线程的方式
作者:cuiweihua
地址:HTTPS://cuiweihua.com/articles/2022/11/02/1667366821393.html

    评论
    0 评论
avatar

取消