Java中线程的简单API介绍

简单介绍一下Thread类的方法

1、set/getName

    设置和获取线程名字

Thread t2 = new Thread(new Runnable() {
    @Override
    public void run() {
        for (int i=0;i<10;i++){
            System.out.println(i);
        }
    }
});
t2.setName("我是线程2");

    使用setName可以给一个线程设置一个名字

Thread t1 = new Thread(){
    @Override
    public void run() {
        for (int i=0;i<10;i++){
            System.out.println(this.getName()+i);
        }
    }
};

使用getName()方法可以获得线程的名字

2、获取当前线程对象

Thread t1 = new Thread(){
    @Override
    public void run() {
        for (int i=0;i<10;i++){
            System.out.println(Thread.currentThread().getName()+i);
        }
    }
};

使用Thread类的静态方法currentThread可以获得那个当前的线程对象

3、线程休眠

Thread t1 = new Thread(){
    @Override
    public void run() {
        for (int i=0;i<10;i++){
            if (i==5) {
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(getName()+i);
        }
    }
};

    使用Thread类的静态方法sleep方法可以让当前线程休眠多少毫秒,线程在休眠期间,其他线程可以获得CPU资源

4、设置守护线程

t1.setDaemon(true);

    设置一个线程为守护线程, 该线程不会单独执行, 当其他非守护线程都执行结束后, 自动退出。比如垃圾回收线程就是守护线程,要注意的是要将线程设置为守护线程,必须在线程调用start方法之前调用setDaemon方法

5、加入线程

public final void join() throws InterruptedException {
    join(0);
}

    当前线程暂停, 等待指定的线程执行结束后, 当前线程再继续。

6、礼让线程

public static native void yield();

   让线程放弃CPU资源,并不代表其他线程一定能抢到CPU资源,当前线程有可能继续执行。

7、停止线程

public void interrupt()

    调用interupt方法仅仅是在当前线程中打了一个停止的标记,并不是真的停止线程

    要想停止线程,可以将interupt方法和interupted方法一起使用

    看下面代码:

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread(){
        @Override
        public void run() {
            try {
                for (int i=0;i<100000;i++){
                    if (this.interrupted()){
                        System.out.println("我要结束了!!!");
                        throw new InterruptedException();
                    }
                    System.out.println(getName()+i);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    try {
        t1.start();
        Thread.sleep(500);
        t1.interrupt();
    }catch (Exception e){
        e.printStackTrace();
    }
}
    使用异常使线程停止。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值