JAVA高级复习-线程中常用的方法

/**
 * @description:测试线程常用方法
 * @date: 2020/7/25 15:12
 * @author: winson
 */
public class ThreadMethodTest {
    public static void main(String[] args) {
        HelloThread t1 = new HelloThread();
        t1.setName("自定义线程名称T1");
        t1.start();

        //修改主线程名称
        Thread.currentThread().setName("主线程名称");
        for (int i = 0; i < 50; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);

            if (i == 10) {
                try {
                    t1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class HelloThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            try {
                sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(currentThread().getName() + ":" + i);

            //yield()让出当前线程执行权
            if (i % 20 == 0) {
                yield();
            }
        }

        System.err.println("自定义线程是否存活:" + isAlive());
    }
}

posted @ 2020-07-25 15:04  温森  阅读(80)  评论(0编辑  收藏  举报