莆仙生活网
当前位置: 莆仙生活网 > 知识库 >

messagequeue(2)

时间:2025-02-09 20:23:11 编辑:莆仙君
2.2 sleep()1) sleep ()函数有一个参数,通过参数可使线程在指定的时间内进入停滞状态,当指定的时间过后,线程则自动进入可执行状态。2) 当调用sleep ()函数后,线程不会释放它的“锁标志”。例12:class TestThreadMethod extends Thread{class TestThreadMethod extends Thread{public static int shareVar = 0;public TestThreadMethod(String name){super(name);}public synchronized void run(){for(int i=0; i<3; i++){System.out.print(Thread.currentThread().getName());System.out.println(" : " + i);try{Thread.sleep(100); //(4)}catch(InterruptedException e){System.out.println("Interrupted");}}}}public class TestThread{public static void main(String[] args){TestThreadMethod t1 = new TestThreadMethod("t1");TestThreadMethod t2 = new TestThreadMethod("t2");t1.start(); (1)t1.start(); (2)//t2.start(); (3)}}运行结果为:t1 : 0t1 : 1t1 : 2t1 : 0t1 : 1t1 : 2由结果可证明,虽然在run()中执行了sleep(),但是它不会释放对象的“锁标志”,所以除非代码(1)的线程执行完run()函数并释放对象的“锁标志”,否则代码(2)的线程永远不会执行。如果把代码(2)注释掉,并去掉代码(3)的注释,结果将变为:t1 : 0t2 : 0t1 : 1t2 : 1t1 : 2t2 : 2由于t1和t2是两个对象的线程,所以当线程t1通过sleep()进入停滞时,排程器会从线程池中调用其它的可执行线程,从而t2线程被启动。例13:class TestThreadMethod extends Thread{public static int shareVar = 0;public TestThreadMethod(String name){super(name);}public synchronized void run(){for(int i=0; i<5; i++){System.out.print(Thread.currentThread().getName());System.out.println(" : " + i);try{if(Thread.currentThread().getName().equals("t1"))Thread.sleep(200);elseThread.sleep(100);}catch(InterruptedException e){System.out.println("Interrupted");}}}}public class TestThread{public static void main(String[] args){TestThreadMethod t1 = new TestThreadMethod("t1");TestThreadMethod t2 = new TestThreadMethod("t2");t1.start();//t1.start();t2.start();}}运行结果为:t1 : 0t2 : 0t2 : 1t1 : 1t2 : 2t2 : 3t1 : 2t2 : 4t1 : 3t1 : 4由于线程t1调用了sleep(200),而线程t2调用了sleep(100),所以线程t2处于停滞状态的时间是线程t1的一半,从从结果反映出来的就是线程t2打印两倍次线程t1才打印一次。