线程优先级&run()和start()区别

1 run()和start()的区别:

run()不是启动线程的方法,start()才是启动线程的方法。run()只是一个普通的方法,start()才是一个启动线程的方法,底层会调用c或者c++。
看一个例子:

package com.yuxi;

/**
 *
 * run  and start different
 * Created by yuxi on 17/1/26.
 */
public class RunDiffStart {
    public  static  void main(String[] args) {
        //这个是线程启动,打出来的是子线程
        MyThread myThread = new MyThread();
        new Thread(myThread).start();
        //这个只是一个普通的Java方法,可以看到打出来的是main线程
        myThread.run();
    }
    static  class  MyThread implements  Runnable {
        public  void run() {
            System.out.println("this is thread name..."+Thread.currentThread().getName());
        }
    }
}

运行结果是:

this is thread name...main
this is thread name...Thread-0

2 线程优先级和守护线程

线程优先级主要从1到10,默认为5,有点需要特别注意的就是不是说线程优先级高的就一定先执行。可以看一个例子:

package com.yuxi;

/**
 * 线程优先级和守护线程
 * Created by yuxi on 17/1/26.
 */
public class PriorityAndDeamon {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread thread = new Thread(myThread);
        thread.setPriority(1);
        thread.setName("B");

        Thread thread1 = new Thread(myThread);
        thread1.setName("A");
        thread1.setPriority(10);

        thread.start();
        thread1.start();
    }

    static class MyThread implements Runnable {
        public void run() {
            System.out.println("this is thread name..." + Thread.currentThread().getName());
        }
    }
}

运行结果为:

第一次:
this is thread name...B
this is thread name...A
第二次:
this is thread name...A
this is thread name...B

我对守护线程的理解就是:他会在用户线程执行完了,再执行,平时完全没有使用过。也没什么好说的,知道有这么个意思就好了。
其实线程优先级平时开发的时候我们也不会去设置,一般情况都是采用默认的。

参考文章:
http://www.cnblogs.com/skywang12345/p/3479243.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容