Java创建线程的几种方法

创建线程有四种方式,分别是继承Thread类、实现Runnable接口、实现Callable接口

使用线程池

1.通过继承Thread类    

  • 定义Thread类的子类,并重写该类的run()方法,该run()方法将作为线程执行体。

  • 创建Thread子类的实例,即创建了线程对象。

  • 调用线程对象的start()方法来启动该线程。

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("继承Thread,重写run方法创建线程");
    }
}
 
public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
    }
}

2. 通过实现Runnable接口

  • 定义Runnable接口的实现类,并实现该接口的run()方法,该run()方法将作为线程执行体。

  • 创建Runnable实现类的实例,并将其作为Thread的target来创建Thread对象,Thread对象为线程对象。

  • 调用线程对象的start()方法来启动该线程。

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("实现Runnable接口,重写run方法");
    }
}
 
public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

3. 通过实现Callable接口

  • 创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,且该call()方法有返回值。然后再创建Callable实现类的实例。
  • 使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。
  • 使用FutureTask对象作为Thread对象的target创建并启动新线程。
  • 调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
class MyCallableTest implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("创建线程:" + Thread.currentThread().getName());
        return 2;
    }
}
 
public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> task = new FutureTask<>(new MyCallableTest());
        Thread thread = new Thread(task);
        thread.start();
        System.out.println("创建线程的返回结果为:" + task.get());
    }
 
}

4. 使用线程池

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class Pool {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newCachedThreadPool();
        pool.submit(new Runnable() {
            @Override
            public void run() {
                //执行业务逻辑
                for(int i = 1; i <= 100; i++) {
                    System.out.println("线程:" + Thread.currentThread().getName() + "执行了任务" + i + "~");
                }
            }
        });
        pool.submit(new Runnable() {
            @Override
            public void run() {
                //执行业务逻辑
                for(int i = 101; i <= 200; i++) {
                    System.out.println("线程:" + Thread.currentThread().getName() + "执行了任务" + i + "~");
                }
            }
        });
        pool.submit(new Runnable() {
            @Override
            public void run() {
                //执行业务逻辑
                for(int i = 201; i <= 300; i++) {
                    System.out.println("线程:" + Thread.currentThread().getName() + "执行了任务" + i + "~");
                }
            }
        });
    }
}
public class CreateDemo {
    private static ExecutorService threadpool = Executors.newFixedThreadPool(3);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1、执行Runnbale类型的target目标实例,无返回
        threadpool.execute(new RunnableTaskDemo());

        //2、 执行Runnbale类型的target目标实例,无返回,内部类形式
        threadpool.execute(new Runnable() {
            @Override
            public void run() {
                for(int i=0;i<3;i++){
                    System.out.println(Thread.currentThread().getName()+" 轮次:"+i);

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }       
        });

        // 3、提交Callable执行目标实例,有返回
        Future future = threadpool.submit(new CallableTaskDemo());
        System.out.println("异步执行的结果为:" + future.get());
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值