Java之创建线程

共有3种创建线程的方式:

  1. 通过实现Runnable接口(最常用);

     (1)定义Runnable接口的实现类,重写run()方法;
    
     (2)创建Runnable实现类的实例,作为Thread的target创建Thread对象;
    
     (3)调用线程对象的start()方法启动线程。
    
public class MyThread implements Runnable {
    @Override
    public void run() {
        System.out.println("线程需要完成的任务,即线程执行体");
    }
}

public class Main {
    public static void main(String[] args) {

        //创建线程
        MyThread myThread=new MyThread();
        Thread thread=new Thread(myThread);
        
        //启动线程
        thread.start();

    }

}
  1. 通过继承Thread类;

    (1)定义Thread类的子类,重写run()方法;

    (2)创建Thread子类的实例,即创建线程对象;

    (3)调用线程的start()方法,启动线程。

public class MyThread2 extends Thread{

    public void run() {
        System.out.println("线程需要完成的任务,即线程执行体");
    }
}

public class Main {
    public static void main(String[] args) {
    	new MyThread2().start();
    }
}
  1. 通过 Callable 和 Future 创建线程;

    (1)创建 Callable 接口的实现类,并实现 call() 方法,该 call() 方法将作为线程执行体,并且有返回值。

    (2)创建 Callable 实现类的实例,使用 FutureTask 类来包装 Callable 对象,该 FutureTask 对象封装了该 Callable 对象的 call() 方法的返回值。

    (3)使用 FutureTask 对象作为 Thread 对象的 target 创建并启动新线程。

    (4)调用 FutureTask 对象的 get() 方法来获得子线程执行结束后的返回值。

public class MyThread3 implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        //线程执行体,有返回值
        int i = 1;
        return i;
    }
}

public class Main {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
           
        MyThread3 thread3 = new MyThread3();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(thread3);
        //启动线程
        new Thread(futureTask).start();
		//通过get()方法获取返回值
        int result = futureTask.get();
        System.out.println(result);
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值