多线程技术三(线程基本信息和优先级)

目录

线程基本信息和优先级别

获取线程基本信息的方法

线程的优先级


线程基本信息和优先级别

        线程也是对象,系统为线程定义很多方法:优先级、名字等等。这样对于我们需要对多 个线程做管理提供了便利。

获取线程基本信息的方法

线程的常用方法
方法功能
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);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值