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() {
    /**
     * This method is not invoked for the main method thread or "system"
     * group threads created/set up by the VM. Any new functionality added
     * to this method in the future may have to also be added to the VM.
     *
     * A zero status value corresponds to state "NEW".
     */
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    /* Notify the group that this thread is about to be started
     * so that it can be added to the group's list of threads
     * and the group's unstarted count can be decremented. */
    group.add(this);

    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}

1.3实现Callable接口通过FutureTask包装的方式

public class ThirdTreading {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // TODO Auto-generated method stub
        //创建Callable实现类的实现
        Callable<Object> oneCallable = new Tickets<Object>();
        //使用FutureTask类包装Callable对象,该FutureTask对象封装了Callable对象的Call方法的返回值
        FutureTask<Object> oneTask = new FutureTask<Object>(oneCallable);
        //使用FutureTask对象作为Thread对象的target创建
        Thread t = new Thread(oneTask);
        //启动线程
        t.start();
        //调用FutureTask对象的get()来获取子线程执行结束的返回值
        System.out.println(oneTask.get().toString());
    }
}

class Tickets<Object> implements Callable<Object> {
    //创建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;     //线程池数量

    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        ExecutorService executorService1 = Executors.newFixedThreadPool(5);
        for(int i = 0; i<POOL_NUM; i++)
        {
            RunnableThread thread = new RunnableThread();
            executorService1.execute(thread);
        }
        //关闭线程池
        executorService1.shutdown();
    }
}

class RunnableThread implements Runnable
{
    @Override
    public void run()
    {
        System.out.println("通过线程池方式创建的线程:" + Thread.currentThread().getName() + " ");

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值