线程的定义和创建

本文介绍了Java中创建线程的三种方式:继承Thread类、实现Runnable接口以及实现Callable接口。详细讨论了Callable相比于Runnable的优势,如支持返回值和抛出检查异常,并提到了Future和FutureTask在处理返回结果中的作用。
摘要由CSDN通过智能技术生成

线程的定义和创建有三种方式:继承Thread类,实现Runnable接口,实现Callable接口

第一种:继承Thread类

//创建一个乌龟类线程:方法一:继承Thread类
/*步骤:
 * 1.定义一个线程:public class TortoiseThread extends Thread {
 *                      public void run() {} }//重写run方法
 *2.创建线程对象:  Thread thread = new TortoiseThread();
 *3.启动线程:thread.start();
 *4.启动main方法:自动创建main线程
 *5.Thread类的常用方法: thread.start();
 *                      thread.setName();//修改线程的名字
 *                     thread.getPriority()//得到线程的优先级
 *                     thread.setPriority()//修改线程的优先级
 *                     Thread.currentThread()//获取当前线程
 *                     Thread.currentThread().setPriority()
 *                     Thread.currentThread().setName()
 */
public class TortoiseThread extends Thread {
    @Override
    public void run() {//线程体:线程要执行的任务
        while (true) {
            //this.setName("乌龟线程");
            //this.setPriority(Thread.MIN_PRIORITY);
            System.out.println("乌龟领先了  " + this.getName() + "  " + this.getPriority());
        }
    }
}
```java
//创建一个线程对象并启动
public class TestThread {
    public static void main(String[] args) {
        Thread thread = new TortoiseThread()
        thread.setName("乌龟线程1");
        thread.setPriority(Thread.MIN_PRIORITY);//最小的优先级为1,默认优先级为5,最大优先级为10
        thread.start();//启动一个新的线程
        Thread thread2 = new TortoiseThread();
        thread2.setName("乌龟线程2");
        thread2.setPriority(Thread.MIN_PRIORITY);
        thread2.start();
        Thread.currentThread().setName("主线程");//修改主线程的名字
        while (true) {
            System.out.println("兔子领先了  " + Thread.currentThread().getName() + "   " + Thread.currentThread().getPriority());
        }
    }
}

第二种:实现Runnable接口

 //创建一个乌龟线程对象:方法二:实现Runnable接口
    /*步骤:
     *1.定义线程:public class TortoiseRunnable implements Runnable {
     *      public void run() {}   }
     * 2.创建线程对象:Runnable runnable=new TortoiseRunnable();
     *               Thread thread=new Thread(runnable);
     * 3.启动线程  thread.start();
     * 4.继承Thread类 优点:编程简单   缺点:无法继承其他类
     *   实现Runnable接口  优点:可以继承其他类  便于多个线程共享同一个资源   缺点:变成稍微复杂
     */
package com.yue.create2;
public class TestThread2 {//匿名内部类实现Runnable接口
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    System.out.println("乌龟领先了  " + Thread.currentThread().getName() + "  " +              
                    Thread.currentThread().getPriority());
                }

            }
        };
        Thread thread1 = new Thread(runnable, "乌龟线程1");
        thread1.setPriority(Thread.MAX_PRIORITY);
        thread1.start();
        Thread thread2 = new Thread(runnable, "乌龟线程2");
        thread2.setPriority(Thread.MIN_PRIORITY);
        thread2.start();
        Thread.currentThread().setName("主线程");
        while(true){
            System.out.println("兔子领先了   "+Thread.currentThread().getName()+"  "+Thread.currentThread().getPriority());
        }
    }
}

第三种:实现Callable接口
与实行Runnable相比, Callable功能更强大些
•方法名不同
•可以有返回值,支持泛型的返回值
•可以抛出检查异常
•需要借助FutureTask,比如获取返回结果
Future接口
•可以对具体Runnable、Callable任务的执行结果进行取消、查询是否完成、获取结果等。
•FutrueTask是Futrue接口的唯一的实现类
•FutureTask 同时实现了Runnable, Future接口。它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值

package com.yue.create3;
import java.util.Random;
import java.util.concurrent.*;
//创建线程的第三种方式:实现Callable接口
// 优点:可以有返回值,可以抛出任意类型的异常
public class RandomCallable implements Callable<Integer> {//返回一个随机数
    @Override
    public Integer call() throws Exception {
        Thread.sleep(8000);//休眠4秒
        return new Random().nextInt(10);
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建一个线程对象
        Callable<Integer> callable = new RandomCallable();
        FutureTask<Integer> task = new FutureTask<>(callable);
        Thread thread = new Thread(task);
        //启动线程
        thread.start();
        //获取返回值
        System.out.println(task.isDone());
        int result = 0;
        //int result = task.get();//得不到返回值就一直等待
        try {
            result = task.get(5, TimeUnit.SECONDS);//只等待5秒(不管有没有返回结果)
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        System.out.println(task.isDone());
        System.out.println(result);
    }
}

第三种方式代码运行的结果
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值