java学习----------------线程命名、休眠与设置优先级

关于java的学习记录:

1.线程的命名与取得
 * 所有的线程程序的执行,每一次都是不同的而运行结果,以为它会根据自己的情况进行
 * 资源抢占,如果要想区分每一个线程,那么就必须依靠线程的名字。对于线程名字一般
 * 而言会在其启动前进行定义,不建议修改名称或者设置重名
 * 如果要想进行线程名称的操作,可以使用Thread类的如下方法:
 * |-构造方法:public Thread(Runnable target,String name)
 * |-设置名字:public final void setName(String name)
 * |-取得名字:public final String getName()
 * 对于线程名字的操作会出现一个问题,这些方法是属于Thread类里面的,可是如果换回
 * 到线程类(Runnable)这个类并没有继承Thread类,如果要想取得线程名字,那么能够
 * 取得的就是当前执行本方法的线程名字,所以在Thread里面提供有一个方法:
 * |-取得当前线程对象:public static Thread currentThread()
 * 如果在实例化Thread对象的时候没有为其设置名字,那么会自动的进行编号命名
 * 2.线程休眠
 * 所谓的线程休眠指的就是让线程的执行速度稍微变慢一点,休眠的方法:
 * |-休眠public static void sleep(long millis)throws InterruptedException
 * 3.线程优先级
 * 所谓的优先级指的是越高的优先级,越有可能先执行。在Thread类里面提供有一下两个
 * 方法进行优先级操作:
 * |-设置优先级:public final void setPriority(int newPriority)
 * |-取得优先级:public final int getPriority()
 * 发现设置和取得优先级都是使用了int数据类型,对于此内容有三种取值:
 * |-最高优先级:public static final int MAX_PRIORITY  10
 * |-最低优先级:public static final int NORM_PRIORITY  5
 * |-中等优先级:public static final int MIN_PRIORITY   1
 *
 */
public class Demo2 {

    public static void main(String[] args) {
        MyThread mt=new MyThread();
//        new Thread(mt,"自己的线程A").start();
//        new Thread(mt).start();
//        new Thread(mt,"自己的线程B").start();
//        new Thread(mt).start();
//        mt.run();//直接调用   main
        /**
         * 主方法就是一个线程,那么所有在主方法上创建的线程实际上都可以叫做
         * 子线程
         * 线程实际上一直都存在,进程在哪?
         * 每当用java命令去解释一个程序类的时候,对于操作系统而言,都相当于
         * 启动了一个新的进程,而main只相当于新进程中的一个子线程而已
         * 每一个JVM进程启动的时候至少启动了几个线程?
         * |-main线程
         * |-gc线程:负责垃圾收集
         */
//        new Thread(mt,"自己的线程B").start();
//        new Thread(mt,"自己的线程C").start();
        /**
         * 默认情况下,休眠的时候如果设置了多个线程对象,那么所有的想爱你城对象将
         * 一起进行到run()方法(所谓的一起进入实际上是因为先后顺序是在太短了,但
         * 实际上有区别)
         */
        Thread t1=new Thread(mt,"线程A");
        Thread t2=new Thread(mt,"线程B");
        Thread t3=new Thread(mt,"线程C");
        t1.setPriority(Thread.MAX_PRIORITY);
        t2.setPriority(Thread.MIN_PRIORITY);
        t3.setPriority(Thread.MIN_PRIORITY);
        t1.start();
        t2.start();
        t3.start();
        //理论上优先级越高,越有可能先执行
        //主线程属于中等优先级
        
    }

}
class MyThread implements Runnable{
    @Override
    public void run() {
        for(int i=0;i<20;i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+",i="+i);
        }        
    }
}


猜你喜欢

转载自blog.csdn.net/amuist_ting/article/details/80697989