线程的状态

创建:新创建了一个线程对象

可运行:线程对象创建后,其他线程调用了该对象的start()方法。该状态的线程位于可运行线程池中,变得可运行,等待获取cpu执行权

运行:就绪状态的线程获取了CPU执行权,执行程序代码。

阻临时塞阻塞状态是线程因为某种原因放弃CPU使用权,暂时停止运行。直到线程进入就绪状态,才有机会转到运行状态

死亡:线程执行完它的任务时。

1.1 常见线程的方法

Thread(String name)     初始化线程的名字

 getName()             返回线程的名字

 setName(String name)    设置线程对象名

 sleep()                 线程睡眠指定的毫秒数。

 getPriority()             返回当前线程对象的优先级   默认线程的优先级是5

 setPriority(int newPriority) 设置线程的优先级    虽然设置了线程的优先级,但是具体的实现取决于底层的操作系统的实现(最大的优先级是10 ,最小的1 , 默认是5)。

 currentThread()      返回CPU正在执行的线程的对象

 

class ThreadDemo1 extends Thread

{

public ThreadDemo1(){

  

}

public ThreadDemo1( String name ){

   super( name );

}

    

public void run(){

   int i = 0;

   while(i < 30){

  i++;

      System.out.println( this.getName() + " "+ " : i = " + i);

  System.out.println( Thread.currentThread().getName() + " "+ " : i = " + i);

  System.out.println( Thread.currentThread() == this );

  System.out.println( "getId()" + " "+ " : id = " + super.getId() );

  System.out.println( "getPriority()" + " "+ " : Priority = " + super.getPriority() );

   }

}

}

class Demo3 

{

public static void main(String[] args)

{

        ThreadDemo1 th1 = new ThreadDemo1("线程1");

ThreadDemo1 th2 = new ThreadDemo1("线程2");

        // 设置线程名

        th1.setName( "th1" );

th2.setName( "th2" );

        // 设置线程优先级  1 ~ 10

th1.setPriority( 10 );

th2.setPriority( 7 );

// 查看SUN定义的线程优先级范围

System.out.println("max : " + Thread.MAX_PRIORITY );

System.out.println("min : " + Thread.MIN_PRIORITY );

        System.out.println("nor : " + Thread.NORM_PRIORITY );

th1.start();

th2.start();

System.out.println("Hello World!");

}

}

 

posted on 2016-10-18 15:28  眼泪笑我愚昧  阅读(143)  评论(0编辑  收藏  举报

导航