java多线程编程技术详解和实例代码

 java多线程编程技术详解和实例代码

1.   Java和他的API都可以使用并发。

可以指定程序包含不同的执行线程,每个线程都具有自己的方法调用堆栈和程序计数器,使得线程在与其他线程并发地执行能够共享程序范围内的资源,比如共享内存,这种能力被称为多线程编程(multithreading),在核心的C和C++语言中并不具备这种能力,尽管他们影响了JAVA的设计。

2.   线程的生命周期

新线程的生命周期从“新生”状态开始。程序启动线程前,线程一直是“新生”状态;程序启动线程后,线程进入“可运行”状态。“可运行”状态的线程,被认为是正在执行他的任务。

在程序启动线程之前,线程一直处于“等待”状态,只有当另一个线程通知正在等待的线程继续执行时,这个线程才会从“等待”状态恢复到“可运行”状态。

“可运行”状态的线程可以进入“定时等待”状态,等待一个指定的时间段。当时间到达或线程正在等待的某个事件发生时,该线程就会返回“可运行”状态。即使处理器可以使用,处于“定时等待”状态和“等待”状态的线程也不能用它。当处于“可运行”状态的线程正在等待另一个线程执行任务时,如果它提供了可选的等待时间段,则这个线程会进入“定时等待”状态。当另一个线程通知了这个线程,或者当定时的时间段到达时(以先满足的为准),这个线程就会返回到“可运行”状态.。使线程进入“定时等待”状态的另一方法是是处于“可运行”状态的线程睡眠。睡眠线程会在“定时等待”状态维持一个指定的时间段(称为睡眠时间段),过了这段时间,它会返回到“可运行”状态。当线程没有工作要执行时,它会立即睡眠。;例
当线程试图执行某个任务,而任务又不能立即完成,线程就从“可运行”状态转到“阻塞”状态。;例。即使有处理器可供使用,“阻塞”状态的线程也不能使用它。

线程成功完成任务,或者(由于出错)终止了时,“可运行”线程就会进入“终止”状态(有时称“停滞”状态)。
在操作系统级别,JAVA的“可运行”状态通常包含两个独立的状态。当线程首先从“新生”状态转到“可运行”状态,线程处于“就绪”状态。当操作系统将线程给处理器时,线程就从“就绪”状态进入“运行”状态(即开始执行),这也被称为“调度线程”。大多数操作系统中,每个线程被赋予一小段处理器时间(时间片)来执行任务。当时间片到达时,线程就会返回到“就绪”状态,而操作系统将另一个线程给予处理器。

3.   线程优先级与线程调度

JAVA的线程优先级范围为MIN_PRIORITY(常量1)到MAX_PRIORITY(常量10),默认是NORM_PRIORITY(常量5)

4.   创建并执行线程

创建线程推介实现Runnable接口

(1)Runnable与Thread类

// 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   
 

     (2)线程管理与Executor框架

       5为显示的创建线程,但推介使用Executor接口,用来管理Runnable对象的执行。Executor对象创建并管理一组Runnable对象的线程,这组线程就做线程池(thread pool).优点是Executor对象能复用了已经有的线程,减少为每个任务创建新线程的开销,提高性能。

       Executor接口只声明了一个名称为execute的方法,接收一个Runnable实参。Executor会将传递给他的execute方法的每个Runnable对象赋予线程池中可以用的线程。如果没有可以用的线程,则Executor会创建一个新线程,或等待某个线程会成为可用的,并会将这个线程赋予传递给execute方法的Runnable对象。

       ExecutorService接口扩展了Executor接口。

// 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 

5.       线程同步 

(1)线程同步(thread synchronization),协调多个并发线程对共享数据的访问。这种方式同步多个线程,就可以保证访问共享对象的每个线程都能同步地将其他所有线程排除在外,这被称为“互斥”。
另一个方法,使用JAVA内置的监控器(monitor)。每个对象都有一个监控器和监控锁(或内置锁)。监控器保证任何时候监控锁由具有最大可能的唯一一个线程持有。

(2)同步的数据共享:执行原子操作。

// 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 
 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!