Java进阶知识查漏补缺03

java线程的一些方法:

package com.cjf.Thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: Everything
 * Date: 2020-07-01
 * Time: 12:26
 */

//1. start(): 启动当前线程;调用当前线程的run()
//2. run(): 通常需要重写Thread类中的此方法, 将创建的线程要执行的操作声明在此方法中
//3. current Thread():静态方法,返回执行当前代码的线程
//4. getName(): 获取当前线程的名字
//5. setName():设置当前线程的名字
//6.yield():释放当前CPU的执行权
//7.join():在线程A中调用线程B的join方法,A阻塞
//8.sleep(long):让当前线程休眠

//线程的优先级
    //getPriority():获取线程的优先级
    //setPriority(int ):设置线程的优先级

class HelloThread extends Thread{
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i%2==0){
                try {
                    sleep(10);//阻塞一秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+":"+i+"优先级"+Thread.currentThread().getPriority());
            }
            if (i%20==0){
//                Thread.yield();
                //只是当前线程释放了CPU,但是有可能当前线程又重新抢到CPU
            }
        }
    }
}

public class ThreadMethodTest {
    public static void main(String[] args) {
        HelloThread h1 = new HelloThread();
        h1.setName("子线程");
        //设置分线程的优先级
        h1.setPriority(Thread.MAX_PRIORITY);

        h1.start();



        Thread.currentThread().setName("主线程");
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i+"优先级"+Thread.currentThread().getPriority());
            }

            if (i == 20) {
                //当20时,让h1子线程调入执行,且必须执行完
                try {
                    h1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }

    }
}

 

posted @ 2020-07-01 23:49  Tsui98'  阅读(107)  评论(0编辑  收藏  举报