Biblioteca Java - Blame information for rev 8

Subversion Repositories:
Rev:
Rev Author Line No. Line
8 mihai 1 package threadpool2;
2  
3 import java.util.Random;
4 import java.util.concurrent.Executors;
5 import java.util.concurrent.ExecutorService;  
6   public class RunnableTester
7  {
8      public static void main( String[] args )
9     {
10         // create and name each runnable            
11         PrintTask task1 = new PrintTask( "thread1" );
12         PrintTask task2 = new PrintTask( "thread2" );
13         PrintTask task3 = new PrintTask( "thread3" );
14  
15         System.out.println( "Starting threads" );
16  
17         // create ExecutorService to manage threads                        
18         ExecutorService threadExecutor = Executors.newFixedThreadPool( 2 );
19  
20         // start threads and place in runnable state  
21         threadExecutor.execute( task1 ); // start task1
22         threadExecutor.execute( task2 ); // start task2
23         threadExecutor.execute( task3 ); // start task3
24  
25         threadExecutor.shutdown();
26  
27         System.out.println( "Threads started, main ends\n" );
28      } // end main
29   } // end class RunnableTester
30  
31  
32  
33  
34   class PrintTask implements Runnable
35     {
36        private int sleepTime; // random sleep time for thread
37        private String threadName; // name of thread
38        private static Random generator = new Random();
39  
40       // assign name to thread
41       public PrintTask( String name )
42       {
43          threadName = name; // set name of thread
44  
45          // pick random sleep time between 0 and 5 seconds
46          sleepTime = generator.nextInt( 5000 );
47       } // end PrintTask constructor
48  
49       // method run is the code to be executed by new thread
50       public void run()                                    
51      {
52          try // put thread to sleep for sleepTime amount of time
53          {
54            System.out.printf( "%s going to sleep for %d milliseconds.\n",
55                threadName, sleepTime );
56  
57             Thread.sleep( sleepTime ); // put thread to sleep
58          } // end try
59          // if thread interrupted while sleeping, print stack trace
60          catch ( InterruptedException exception )
61          {
62             exception.printStackTrace();
63          } // end catch
64  
65          // print thread name
66          System.out.printf( "%s done sleeping\n", threadName );
67       } // end method run
68    } // end class PrintTask<