Thread

实现线程的三种方法

1.继承线程类Thread

2.实现接口Runnable

3.实现Callable类

继承Thread

public class A extends Thread{
    public void run(){
        for (int i = 0; i < 5; i++) {
            System.out.println("A thread "+i+" 执行");
            try{
                Thread.sleep(7);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

通过接口Runnable

public class ThreadB implements Runnable{

    public void run(){
        for (int i = 0; i < 100000; i++) {
            System.out.println("back Thread execute No.+"+i);
            try{
                Thread.sleep(7);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

通过Callable实现

    public class C implements Callable<String>{
        public String call() throws Exception{
            try{
                Thread.sleep(500);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            return "this is call ";
        }
    }

线程通过Thread.interruput()进行终端,

在线程中可以通过 Boolean isInterruputed()进行判断是否有中断请求

boolean interrupted()测试当前线程是否已经中断

线程的生命周期有一下几个阶段

new 创建

runnable 就绪状态

running 运行状态

blocked 堵塞状态

dead 死亡状态

什么是守护线程?

简单的溯就是后台线程,不需要手动去通知管理其状态,

在线程开始前通过setDeamon(boolean on)进行设置

        A a = new A();
        ThreadB threadB = new ThreadB();
        Thread b = new Thread(threadB);
        b.setDaemon(true);
        a.start();
        b.start();
        A a = new A();
        a.start();
        ThreadB threadB = new ThreadB();
        for (int i = 0; i < 5; i++) {
            new Thread(threadB,"Thread B No. "+i).start();
        }
        Thread thread = Thread.currentThread();
        System.out.println("this is main Thread "+thread.getName());
        Thread thread = new Thread(new Main(),"main thread");
        System.out.println("thread is start");
        thread.start();
        Thread.sleep(500);
        System.out.println("interupt thread");
        thread.interrupt();
        System.out.println("thread is interupt: "+thread.isInterrupted());
        System.out.println(thread.getState());

前台线程是保证执行完,而后台线程则不一定保证执行完

当非守护线程结束退出时,即使守护线程仍在进行,进程仍将结束。即有可能当进程结束时,守护线程仍在运行。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值