Java多线程5--线程的基本信息

线程的几个方法我们经常要用到

isAlive()            判断线程是否还活着,即线程是否还未终止

getPriority()          获得线程的优先级数值

setPriority()          设置线程的优先级数值

setName()            给线程命名

getName()            获取线程的名字

currentThread()           取得当前正在运行的线程对象也就是线程本身

新建一个类MyThread继承Runnable

public class MyThread implements Runnable {

	private boolean flag=true;
	private int num=0;
	@Override
	public void run() {
		while(flag){
			System.out.println(Thread.currentThread().getName()+"-->"+num++);
		}
	}
	public void stop(){
		flag=false;
	}

}

建一个测试类InfoDemo01

public class InfoDemo01 {

	public static void main(String[] args) throws InterruptedException {
		MyThread t1=new MyThread();
		Thread proxy =new Thread(t1,"test1");
		proxy.setName("测试1");
		
		System.out.println(proxy.getName());
		System.out.println(Thread.currentThread().getName());//当前线程名称即main
		
		proxy.start();
		System.out.println("启动后的状态:"+proxy.isAlive());
		Thread.sleep(20);
		t1.stop();
		Thread.sleep(1000);
		System.out.println("停止后的状态:"+proxy.isAlive());
	}

}

运行结果为

接下来建立一个类InfoDemo02来测试一下优先级

优先级是指执行的概率,不代表绝对的优先顺序,优先级低的也会执行

public class InfoDemo02 {

	public static void main(String[] args) throws InterruptedException {
		MyThread it=new MyThread();
		Thread p1=new Thread(it,"测试1");
		MyThread it2=new MyThread();
		Thread p2=new Thread(it2,"测试2");
		
		p1.setPriority(Thread.MIN_PRIORITY);//设置优先级
		p2.setPriority(Thread.MAX_PRIORITY);
		
		p1.start();
		p2.start();
		
		Thread.sleep(20);
		it.stop();
		it2.stop();

	}

}

运行结果里优先级高的执行概率大一些

猜你喜欢

转载自blog.csdn.net/qq_36986067/article/details/81333141
今日推荐