Java多线程的4种创建方法

Java多线程的4种创建方法,第1张

Java多线程的4种创建方法 1、Java多线程的创建方法(4种) 1.1继承Thread
public class FirstTreading{
    public static void main(String[] args) {
        MyTread myTread = new MyTread();
        myTread.start();
    }
}
class MyTread extends Thread{
    public void run(){
        System.out.println("继承Thread类方法");
    }
}

Thread 类本质上是实现了 Runnable 接口的一个实例,代表一个线程的实例。 启动线程的唯一方法就是通过 Thread 类的 start()实例方法。 start()方法是一个 native 方法,它将启动一个新线程,后执行 run()方法。

1.2实现Runnable接口
public class SecondThreading {
    public static void main(String[] args) {
        MyTread2 myTread2 = new MyTread2();
        Thread thread = new Thread(myTread2);
        thread.start();
    }
}
class MyTread2 implements Runnable {
    @Override
    public void run() {
        System.out.println("第二种方法:实现Runnable");
    }
}

当传入一个Runnable target 参数给Thread后会调用target.run()

@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

Thread的Start源码

public synchronized void start() {
    
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    
    group.add(this);

    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            
        }
    }
}
1.3实现Callable接口通过FutureTask包装的方式
public class ThirdTreading {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // TODO Auto-generated method stub
        //创建Callable实现类的实现
        Callable oneCallable = new Tickets();
        //使用FutureTask类包装Callable对象,该FutureTask对象封装了Callable对象的Call方法的返回值
        FutureTask oneTask = new FutureTask(oneCallable);
        //使用FutureTask对象作为Thread对象的target创建
        Thread t = new Thread(oneTask);
        //启动线程
        t.start();
        //调用FutureTask对象的get()来获取子线程执行结束的返回值
        System.out.println(oneTask.get().toString());
    }
}

class Tickets implements Callable {
    //创建Callable接口的实现类 ,并实现Call方法
    @Override
    public Object call() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("是通过实现Callable接口通过FutureTask包装器来实现的线程");
        return (Object) "第三种方法";
    }
}
 
1.4通过线程池创建线程 
public class FourthThreading{

    private static int POOL_NUM = 10;     //线程池数量

    
    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        ExecutorService executorService1 = Executors.newFixedThreadPool(5);
        for(int i = 0; i

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/5120969.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-17
下一篇2022-11-17

发表评论

登录后才能评论

评论列表(0条)