线程常用方法及优先级

常用方法

* Thread.currentThread()
* setName() :设置名称
* getName() :获取名称
* isAlive() :判断状态

 

线程类  (下面两组代码基于它)

Demo01.java

package cn.Thread02;

public class Demo01 implements Runnable {
    private boolean flag=true;
    private int num=0;

    @Override
    public void run() {
        while(flag) {
            System.out.println(Thread.currentThread().getName()+"--->"+num++);
//            if(num==50) {
//                stop();
//            }
        }
    }
    public void stop() {
        this.flag=!this.flag;
    }
}

基本方法

InfoDemo01.java

package cn.Thread02;
/*
 * Thread.currentThread()
 * setName() :设置名称
 * getName() :获取名称
 * isAlive() :判断状态     
 */
public class InfoDemo01 {
    public static void main(String[] args) throws InterruptedException {
        Demo01 it=new Demo01();
        Thread proxy=new Thread(it,"It");
        proxy.setName("text");
        System.out.println(proxy.getName());
        System.out.println(Thread.currentThread().getName()); //main线程
        proxy.start(); 
        System.out.println("启动后的状态"+proxy.isAlive());
        Thread.sleep(10);
        it.stop();
        Thread.sleep(100);
        System.out.println("关闭后的状态"+proxy.isAlive());
    
    }
}

效果:

优先级测试代码

InfoDemo02.java

package cn.Thread02;
/*
 * 优先级    概率     不是绝对的先后顺序
 * MAX_PRIORITY  10
 * NORM_PRIORITY 5 (默认)
 * MIN_PRIORITY  1
 */
public class InfoDemo02 {
    public static void main(String[] args) throws InterruptedException {
        Demo01 it=new Demo01();
        Thread p1=new Thread(it,"It1");
        Demo01 it2=new Demo01();
        Thread p2=new Thread(it2,"It2"); 
        p1.setPriority(Thread.MIN_PRIORITY);  //设置优先级
        p2.setPriority(Thread.MAX_PRIORITY);
        p1.start();
        p2.start();
        
        
        Thread.sleep(10);
        it.stop();
        it2.stop();
    }
}

效果:

 

posted on 2019-07-26 19:47  Mentality  阅读(146)  评论(0编辑  收藏  举报