码迷,mamicode.com
首页 > 编程语言 > 详细

01线程的一些方法

时间:2018-05-06 22:19:07      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:一段   执行   stat   sda   catch   none   优先   string   code   

1.获取线程Id
        System.out.println(new Thread().getId());
2.线程优先级
线程优先级低并不意味着得不到处理器执行,而只是执行的频率低一点而已。而且线程的优先级一般不用我们程序员去主动设置
Thread.MIN_PRIORITY = 1
Thread.NORM_PRIORITY = 5;
Thread.MAX_PRIORITY = 10;

        Thread t1 = new Thread("t1");
        System.out.println("t1 线程优先级:"+t1.getPriority());

        t1.setPriority(Thread.MAX_PRIORITY);
        System.out.println("t1 线程优先级:"+t1.getPriority());

3.休眠

线程执行过程中让程序停一段时间之后再执行,这个停止一段时间也叫做休眠

休眠其实只是把正在运行的线程阻塞掉,放到阻塞队列里,等指定的时间一到,再从阻塞队列里出来而已
public static void main(String[] args) {
    System.out.println(1);

    try {
        Thread.sleep(1000L);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    System.out.println(2);
}

5.守护线程

   只有在线程未启动的时候才能设置该线程是否为守护线程

main 线程并不是守护线程。从普通线程中生成的线程默认是普通线程,从守护线程中生成的线程默认是守护线程
System.out.println("main线程是否是守护线程:" + Thread.currentThread().isDaemon());
Thread t1 = new Thread("t1");
System.out.println("t1线程是否是守护线程:" + t1.isDaemon());
t1.setDaemon(true);
System.out.println("t1线程是否是守护线程:" + t1.isDaemon());

6.让出本次处理器时间片


static void yield():表示放弃此次时间片时间,等待下次执行。

7.等待另一线程执行结束

void join() 等待该线程终止才能继续执行。


Thread tt1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i < 5; i++){
                    System.out.println(i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"tt1");
        tt1.start();

        Thread tt2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    tt1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("====线程tt1执行完了,该t2了");
            }
        });

        tt2.start();

 

 

01线程的一些方法

标签:一段   执行   stat   sda   catch   none   优先   string   code   

原文地址:https://www.cnblogs.com/wjh123/p/8999717.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!