Java创建简单的线程

线程(Thread)

  • 线程(thread)是操作系统能够进行运算调度的最小单位。

Java创建线程三种方式

  • 继承Thread
  • 实现接口Runnable
  • 实现Callable接口,重写call(),利用FutureTask包装Callable,并作为task传入Thread构造函数;

方式一:

  • 继承Thread,重写run()。
  • 实例化MyThreadOne,通过调用MyThreadOne的start()方法启动线程。
public class MyThreadOne extends Thread{
    public void run(){
        System.out.println("继承Thread类实现线程!");
    }
    public static void main(String[] args) {
        MyThreadOne thread1 = new MyThreadOne();
        MyThreadOne thread2 = new MyThreadOne();
        MyThreadOne thread3 = new MyThreadOne();
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

方式二:

  • 实现Runnable接口,重写run()
  • 如果自己的类已经继承了别的类,那就只能实现Runnable接口了。
  • 实例化Thread,再传入MyThreadOne的实例,通过调用Thread的start()方法。
public class MyThreadTwo implements Runnable{
    @Override
    public void run() {
        System.out.println("实现接口Runable实现线程");
    }
    public static void main(String[] args) {
        MyThreadOne thread1 = new MyThreadOne();
        for (int i = 0; i<10; i++){
            new Thread(thread1).start();
        }
    }
}

方式三:

  • 实现Callable接口,重写call(),利用FutureTask包装Callable,并作为task传入Thread构造函数。
  • 定义MyThreadThree实现Callable接口;
  • 重写call();
  • 创建FutureTask的对象;FutureTask中定义了run(),run()内部调用了call(),并保存了call()的返回值;
  • 创建Thread的对象,传入参数Runnable接口;
  • 启动线程,thread.start();
  • 可通过FutureTask类的get()方法获得线程执行结束后的返回值,即call的返回值;
public class MyThreadThree implements Callable<Integer> {
    int i = 0;
    @Override
    public Integer call() throws Exception {
        System.out.println("执行call方法前i为:"+i);
        i++;
        return i;
    }
    public static void main(String[] args) throws Exception {
        FutureTask<Integer> task = new FutureTask<Integer>(new MyThreadThree());
        new Thread(task).start();
        try {
            System.out.println("执行call方法返回值i为:"+task.get());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值