class Test { public static void main( String args[] ) throws Exception{ InfinityThread shortLived = new InfinityThread( ); shortLived.setDaemon( true ); shortLived.start(); Thread.currentThread().sleep( 10 ); System.out.println( "Bye"); } } class InfinityThread extends Thread { public void run() { while (true) { System.out.println( "From: " + getName() ); System.out.flush(); yield(); } } }
From: Thread-4 From: Thread-4 From: Thread-4 From: Thread-4 From: Thread-4 From: Thread-4 From: Thread-4 From: Thread-4 From: Thread-4 Bye
class Test { public static void main( String args[] ) throws Exception{ NiceThread missManners = new NiceThread( ); missManners.setPriority( 2 ); missManners.start(); Thread.currentThread().sleep( 5 ); missManners.pleaseStop(); } } class NiceThread extends Thread { protected boolean stopRequested = false; public void pleaseStop() { stopRequested = true; } public void run() { while (!stopRequested) System.out.println( "From: " + getName() ); System.out.println( "The End" ); } }
From: Thread-2 From: Thread-2 From: Thread-2 From: Thread-2 From: Thread-2 The End
class Test { public static void main( String args[] ) throws Exception { NotPoliteThread outOfMyWay = new NotPoliteThread( ); outOfMyWay.setPriority( 2 ); outOfMyWay.start(); Thread.currentThread().sleep( 5 ); outOfMyWay.stop(); } } class NotPoliteThread extends Thread { public void run() { while (1 < 2) { System.out.println( "From: " + getName() ); System.out.flush(); } System.out.println( "The End" ); } }
From: Thread-2 From: Thread-2 From: Thread-2 From: Thread-2 From: Thread-2