23/365 java 线程状态

1.线程的五大状态

 2.停止线程

不建议使用stop(),destory()等JDK不推荐使用的方法

可以设置一个状态位来终止线程

package oop;

public class D13 implements Runnable{
    private boolean live = true;

    @Override
    public void run() {
        int i = 0;
        while(live){
            System.out.println("Thread is live " + i++);
        }
    }

    public void stop(){
        this.live = false;
        System.out.println("Stop thread");
    }

    public static void main(String[] args) {
        D13 d = new D13();
        new Thread(d).start();

        for(int i=0;i<1000;i++){
            if(i==900){
                d.stop();
            }
            System.out.println("Main is running " + i);
        }
    }
}

3.线程休眠

sleep(int n ) 参数的单位为ms

调用sleep()要catch InterruptedException异常

sleep()完成后,线程进入就绪状态

sleep()不会释放锁

以下代码为用sleep()每隔5s打印一次系统时间

public static void main(String[] args) {
        while(true){
            try {
                Thread.sleep(5000);
                Date d = new Date(System.currentTimeMillis());
                System.out.println(new SimpleDateFormat("hh:mm:ss").format(d));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

结果:

 

4.线程礼让

当前的线程从运行状态转为就绪状态,CPU重新进行调度,但不一定礼让成功,因为CPU有可能选择继续运行该线程。

public class D15 {
    public static void main(String[] args) {
        TestYield t = new TestYield();
        new Thread(t,"Thread A").start();
        new Thread(t,"Thread B").start();
    }
}


class TestYield implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " begin");
        Thread.yield();
        System.out.println(Thread.currentThread().getName() + " end");
    }
}

结果:

 可以看到Thread B在这一次运行中成功地礼让了A

5.线程强制执行

join() 该线程变为运行状态,且该线程完全执行完,其他线程才能执行

需要抛出异常

public class D16 {

    public static void main(String[] args) throws InterruptedException{
        TestJoin j = new TestJoin();
        Thread t = new Thread(j);
        t.start();

        for (int i = 0; i < 100; i++) {
            if(i==50){
                t.join();
            }
            System.out.println("Main is running " + i);
        }
    }
}

class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("This thread runs first " + i);
        }
    }
}

结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值