欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-29 15:38:46
 java多线程编程技术详解和实例代码 1.   java和他的api都可以使用并发。 可以指定程序包含不同的执行线程,每个线程都具有自己...

 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 
 

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