目录
线程基本信息和优先级别
线程也是对象,系统为线程定义很多方法:优先级、名字等等。这样对于我们需要对多 个线程做管理提供了便利。
获取线程基本信息的方法
方法 | 功能 |
isAlive() | 判断线程是否还“活”着,即线程是否还未终止 |
getPriority() | 获得线程的优先级数值 |
setPriority() | 设置线程的优先级数值 |
setName() | 给线程一个名字 |
getName() | 取得线程的名字 |
currentThread() | 取得当前正在运行的线程对象,也就是取得自己本身 |
public class TestThread {
public static void main(String[ ] argc) throws Exception {
Runnable r = new MyThread();
Thread t = new Thread(r, "Name test");//定义线程对象,并传入参数;
t.start();//启动线程;
System.out.println("name is: " + t.getName());//输出线程名称;
Thread.currentThread().sleep(5000);//线程暂停5分钟;
System.out.println(t.isAlive());//判断线程还在运行吗?
System.out.println("over!");
}
}
class MyThread implements Runnable {
//线程体;
public void run() {
for (int i = 0; i < 10; i++)
System.out.println(i);
}
}
线程的优先级
处于就绪状态的线程,会进入“就绪队列”等待 JVM 来挑选。
线程的优先级用数字表示,范围从 1 到 10,一个线程的缺省优先级是 5。
使用下列方法获得或设置线程对象的优先级。
int getPriority();
void setPriority(int newPriority);
优先级低只是意味着获得调度的概率低。并不是绝对先调用优先级高的线程 后调用优先级低的线程。
public class TestThread {
public static void main(String[ ] args) {
Thread t1 = new Thread(new MyThread(), "t1");
Thread t2 = new Thread(new MyThread(), "t2");
t1.setPriority(1);
t2.setPriority(10);
t1.start();
t2.start();
}
}
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}