实现Callable接口实现线程创建及线程注意事项包括线程状态,一些API


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Test6 {

    public static void main(String[] args) {
        test2();
        test1();
        test();
    }
    static void test2(){
        //3.Callable
        // 3.1、创建Callable接口的实现类,实现call() 方法
        // 3.2、创建Callable实现类实例,通过FutureTask类来包装Callable对象,该对象封装了Callable对象的call()方法的返回值。
      // 3.3、将创建的FutureTask对象作为target参数传入,创建Thread线程实例并启动新程。
        // 3.4、调用FutureTask对象的get方法获取返回值。
        Test2 test2 = new Test2();
        FutureTask task = new FutureTask(test2);
        Thread thread = new Thread(task);
        //启动线程
        thread.start();
        //获取线程的返回值
        try {
            System.out.println(task.get().toString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
    static void test1(){
        //2.Runable 方式
        Thread t = new Thread(new Test1(), "乌龟");
        Thread r = new Thread(new Test1(), "兔子");
        //启动线程,不能多次调用
        t.start();
        r.start();
    }
    static void test(){
        //1.继承
        Test7 thread_1 = new Test7("thread_一");
        Test7 thread_2 = new Test7("thread_二");
        //启动start()
        thread_1.start();
        thread_2.start();
    }
}
//3.Callable
class Test2 implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        int sum=0;
        for(int i =1;i<=100;i++)
        {
            sum+=i;
        }
        return sum;
    }
}


//2.实现Runnable
class Test1 implements Runnable{

    @Override
    public void run() {
        for (int i = 100;i>0;i--)
        {
            System.out.println(Thread.currentThread().getName()+":领先了,还剩多少米"+i);
        }
    }
}

//1.继承Thread
class Test7 extends Thread{
    Test7(String name){
        super(name);
    }
    @Override
    public void run() {
        int i = 0;
        while (true){
            System.out.println(getName()+"=="+i);
            i++;
        }
    }
}

运行截图
请添加图片描述
请添加图片描述
请添加图片描述

线程注意事项

start(启动线程)不能多次调用
线程状态:
新建:新建对象,未获得资源
就绪:获得除cpu以外的以外资源
运行:获得cpu使用权
等待/阻塞:中途停止cpu使用,即阻塞,等待重新进入就绪状态
死亡:系统回收利用资源

API

获取当前线程的名字:currentThread().getName()
sleep()休眠当前执行的线程
yield()获得的时间片让出,使得成为最后执行的线程
interrupted()判断当前线程是否中断
setPriority()设置优先级
改变共享变量值中断run()执行
interrupt()抛出中断被阻塞进程异常,使得提前结束阻塞状态

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梅花与竹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值