线程的停止&休眠&礼让&强制执行&优先级

线程的停止

//建议线程正常停止 --> 利用次数,不建议死循环
//建议使用标志位 --> 设置一个 flag 标志位
//不使用 stop 或 destroy 等过时方法
public class TestStop implements Runnable{

    //1、设置一个标志位
    private boolean flag = true;

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

    //2、实在一个公开的方法停止线程,转换标志位
    public void stop(){
        this.flag = false;
    }

    public static void main(String[] args) {

        TestStop testStop = new TestStop();

        new Thread(testStop).start();

        for (int i = 0; i < 100; i++) {
            System.out.println("main" + i);
            if (i == 90) {
                testStop.stop();
                System.out.println("线程停止了");
            }
        }
    }
}

线程的休眠

//延时200ms
Thread.sleep(200);

线程的礼让—— yield

比如有A,B两个线程,如果在A运行时进行礼让,此时A从运行态转为就绪态,让CPU重新调度;有可能礼让成功,改为B运行,也有可能失败,仍是A在运行。

thread.yield();

线程的强制执行—— join

就是某线程是VIP,可以插队运行

thread.join();

线程的优先级—— priority

优先级越高的线程,所获得的资源的就越多,有更大的可能性先执行,而不是一定会先执行,具体看CPU的调度。所以有可能出现低优先级线程先执行的情况,就是所谓的优先级倒置,引起性能问题
注意:先设置优先级,再启动;即优先级的设定在start()调度之前

getPriority().setPriority(int xxx)

你可能感兴趣的:(线程的停止&休眠&礼让&强制执行&优先级)