// Fig. 4.1: PrintTask.java
// PrintTask class sleeps for a random time from 0 to 5 seconds
import java.util.Random;
public class PrintTask implements Runnable
{
private final int sleepTime; // random sleep time for thread
private final String taskName; // name of task
private final static Random generator = new Random();
public PrintTask( String name )
{
taskName = name; // set task name
// pick random sleep time between 0 and 5 seconds
sleepTime = generator.nextInt( 5000 ); // milliseconds
} // end PrintTask constructor
// method run contains the code that a thread will execute
public void run()
{
try // put thread to sleep for sleepTime amount of time
{
System.out.printf( "%s going to sleep for %d milliseconds.\n",
taskName, sleepTime );
Thread.sleep( sleepTime ); // put thread to sleep
} // end try
catch ( InterruptedException exception )
{
System.out.printf( "%s %s\n", taskName,
"terminated prematurely due to interruption" );
} // end catch
// print task name
System.out.printf( "%s done sleeping\n", taskName );
} // end method run
} // end class PrintTask
// Fig. 4.2 ThreadCreator.java
// Creating and starting three threads to execute Runnables.
import java.lang.Thread;
public class ThreadCreator
{
public static void main( String[] args )
{
System.out.println( "Creating threads" );
// create each thread with a new targeted runnable
Thread thread1 = new Thread( new PrintTask( "task1" ) );
Thread thread2 = new Thread( new PrintTask( "task2" ) );
Thread thread3 = new Thread( new PrintTask( "task3" ) );
System.out.println( "Threads created, starting tasks." );
// start threads and place in runnable state
thread1.start(); // invokes task1抯 run method
thread2.start(); // invokes task2抯 run method
thread3.start(); // invokes task3抯 run method
System.out.println( "Tasks started, main ends.\n" );
} // end main
} // end class RunnableTester
// Fig. 4.3: TaskExecutor.java
// Using an ExecutorService to execute Runnables.
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class TaskExecutor
{
public static void main( String[] args )
{
// create and name each runnable
PrintTask task1 = new PrintTask( "task1" );
PrintTask task2 = new PrintTask( "task2" );
PrintTask task3 = new PrintTask( "task3" );
System.out.println( "Starting Executor" );
// create ExecutorService to manage threads
ExecutorService threadExecutor = Executors.newCachedThreadPool();
// start threads and place in runnable state
threadExecutor.execute( task1 ); // start task1
threadExecutor.execute( task2 ); // start task2
threadExecutor.execute( task3 ); // start task3
// shut down worker threads when their tasks complete
threadExecutor.shutdown();
System.out.println( "Tasks started, main ends.\n" );
} // end main
} // end class TaskExecutor
// Adds integers to an array shared with other Runnables
import java.lang.Runnable;
public class ArrayWriter implements Runnable
{
private final SimpleArray sharedSimpleArray;
private final int startValue;
public ArrayWriter( int value, SimpleArray array )
{
startValue = value;
sharedSimpleArray= array;
} // end constructor
public void run()
{
for ( int i = startValue; i < startValue + 3; i++ )
{
sharedSimpleArray.add( i ); // add an element to the shared array
} // end for
} // end method run
} // end class ArrayWrite
// Fig 5.2: SharedArrayTest.java
// Executes two Runnables to add elements to a shared SimpleArray.
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
public class SharedArrayTest
{
public static void main( String[] arg )
{
// construct the shared object
SimpleArray sharedSimpleArray = new SimpleArray( 6 );
// create two tasks to write to the shared SimpleArray
ArrayWriter writer1 = new ArrayWriter( 1, sharedSimpleArray );
ArrayWriter writer2 = new ArrayWriter( 11, sharedSimpleArray );
// execute the tasks with an ExecutorService
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute( writer1 );
executor.execute( writer2 );
executor.shutdown();
try
{
// wait 1 minute for both writers to finish executing
boolean tasksEnded = executor.awaitTermination(
1, TimeUnit.MINUTES );
if ( tasksEnded )
System.out.println( sharedSimpleArray ); // print contents
else
System.out.println(
"Timed out while waiting for tasks to finish." );
} // end try
catch ( InterruptedException ex )
{
System.out.println(
"Interrupted while wait for tasks to finish." );
} // end catch
} // end main
} // end class SharedArrayTest
// Fig.5.3 : SimpleArray.java
// Class that manages an integer array to be shared by multiple
// threads with synchronization.
import java.util.Random;
public class SimpleArray
{
private final int array[]; // the shared integer array
private int writeIndex = 0; // index of next element to be written
private final static Random generator = new Random();
// construct a SimpleArray of a given size
public SimpleArray( int size )
{
array = new int[ size ];
} // end constructor
// add a value to the shared array
public synchronized void add( int value )
{
int position = writeIndex; // store the write index
try
{
// put thread to sleep for 0-499 milliseconds
Thread.sleep( generator.nextInt( 500 ) );
} // end try
catch ( InterruptedException ex )
{
ex.printStackTrace();
} // end catch
// put value in the appropriate element
array[ position ] = value;
System.out.printf( "%s wrote %2d to element %d.\n",
Thread.currentThread().getName(), value, position );
++writeIndex; // increment index of element to be written next
System.out.printf( "Next write index: %d\n", writeIndex );
} // end method add
// used for outputting the contents of the shared integer array
public String toString()
{
String arrayString = "\nContents of SimpleArray:\n";
for ( int i = 0; i < array.length; i++ )
arrayString += array[ i ] + " ";
return arrayString;
} // end method toString
} // end class SimpleArray
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有