`
kkkloveyou
  • 浏览: 26182 次
文章分类
社区版块
存档分类
最新评论

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

 

分享到:
评论

相关推荐

    Java多线程编程实战指南(核心篇)

    Java多线程编程实战指南(核心篇) 高清pdf带目录 随着现代处理器的生产工艺从提升处理器主频频率转向多核化,即在一块芯片上集成多个处理器内核(Core),多核处理器(Multicore Processor)离我们越来越近了――如今...

    java多线程编程实战指南 核心篇 代码

    《Java多线程编程实战指南(核心篇)》以基本概念、原理与方法为主线,辅以丰富的实战案例和生活化实例,并从Java虚拟机、操作系统和硬件多个层次与角度出发,循序渐进、系统地介绍Java平台下的多线程编程核心技术及...

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

    主要介绍了 java多线程编程技术详解和实例代码的相关资料,需要的朋友可以参考下

    java多线程核心技术

    资深Java专家10年经验总结,全程案例式讲解,首本全面介绍Java多线程编程技术的专著 结合大量实例,全面讲解Java多线程编程中的并发访问、线程间通信、锁等最难突破的核心技术与应用实践 Java多线程无处不在,如...

    Java多线程设计模式(含实例源码)

    Java多线程设计模式,通过对多线程环境的分析,抽象出典型的多线程模型,结合Java编程语言的特性,总结出经典的多线程设计模式,通过本资料的学习,足以让您掌握如何使用JAVA编程技术来解决多线程问题,结合本书实例...

    JAVA上百实例源码以及开源项目源代码

     Java局域网通信——飞鸽传书源代码,大家都知道VB版、VC版还有Delphi版的飞鸽传书软件,但是Java版的确实不多,因此这个Java文件传输实例不可错过,Java网络编程技能的提升很有帮助。 Java聊天程序,包括服务端和...

    java并发编程2

    java并发编程pdf文档第二部分:Java并发编程实战.pdf、Java多线程编程核心技术.pdf、实战Java高并发程序设计.pdf

    java源码包---java 源码 大量 实例

     Java局域网通信——飞鸽传书源代码,大家都知道VB版、VC版还有Delphi版的飞鸽传书软件,但是Java版的确实不多,因此这个Java文件传输实例不可错过,Java网络编程技能的提升很有帮助。 Java聊天程序,包括服务端和...

    Java经典编程300例(完整版+源码

    多线程、 网络通信和数据库操作。 本书所精选的实例都是一线开发人员在实际项目中所积累的,并进行了技术上的解析,给出了详细的实现过程。读者通过对本书的学习,能够提高开发的能力。 本书提供了大量的源程序、...

    Java高手真经(编程基础卷)光盘全部源码 免积分

    javathread.zip 10.Java多线程编程(线程池、生产者消费者、存取款实例) javautil.zip 11.Java常用实体类 javaxml.zip 14.XML属性文件 第4部分(6个程序包) javagui.zip 15.Java GUI库对比实例 javaawt.zip ...

    java concurrent source code

    资深Java专家10年经验总结,全程案例式讲解,首本全面介绍Java多线程编程技术的专著 结合大量实例,全面讲解Java多线程编程中的并发访问、线程间通信、锁等最难突破的核心技术与应用实践 封底 Java多线程无处不在,...

    《Java并发编程的艺术》源代码

    第4章从介绍多线程技术带来的好处开始,讲述了如何启动和终止线程以及线程的状态,详细阐述了多线程之间进行通信的基本方式和等待/通知经典范式。 第5章介绍Java并发包中与锁相关的API和组件,以及这些API和组件的...

    JAVA学习视频之Java8高级编程(2)

    这些实例展示了Java高级编程技术在实际开发中的应用场景,帮助开发者提高代码的效率和质量。通过学习和理解更高级的Java编程技巧,我们能够更好地应对复杂的编程需求,提升软件开发的水平和竞争力。

    JAVA学习视频之Java8高级编程(1)

    这些实例展示了Java高级编程技术在实际开发中的应用场景,帮助开发者提高代码的效率和质量。通过学习和理解更高级的Java编程技巧,我们能够更好地应对复杂的编程需求,提升软件开发的水平和竞争力。

    JAVA学习视频之Java8高级编程(3)

    这些实例展示了Java高级编程技术在实际开发中的应用场景,帮助开发者提高代码的效率和质量。通过学习和理解更高级的Java编程技巧,我们能够更好地应对复杂的编程需求,提升软件开发的水平和竞争力。

    多线程核心

    Java多线程编程核心技术是资深Java专家10年经验总结,全程案例式讲解,首本全面介绍Java多线程编程技术的专著。本书以浅白的措辞,结合大量实例,全面讲解Java多线程编程中的并发访问、线程间通信、锁等最难突破的...

    JAVA上百实例源码以及开源项目

     Java局域网通信——飞鸽传书源代码,大家都知道VB版、VC版还有Delphi版的飞鸽传书软件,但是Java版的确实不多,因此这个Java文件传输实例不可错过,Java网络编程技能的提升很有帮助。 Java聊天程序,包括服务端和...

    Java高手真经(编程基础卷)光盘全部源码

    javathread.zip 10.Java多线程编程(线程池、生产者消费者、存取款实例) javautil.zip 11.Java常用实体类 javaxml.zip 14.XML属性文件 第4部分(6个程序包) javagui.zip 15.Java GUI库对比实例 javaawt.zip 16....

    synchronized用法大全实例

    java多线程编程核心技术synchronized实例大全,同步方法,同步语句块,类锁,对象锁全都用代码来展现出来

    精通Java:JDK、数据库系统开发Web开发(实例代码)

    精通Java:JDK、数据库系统开发Web开发(实例代码) 《精通Java:JDK、数据库系统开发Web开发》全书共分27章,内容涵盖了Java编程环境概述、基础语法、面向对象软件设计方法、线程、数据集合、网络编程、图形编程、...

Global site tag (gtag.js) - Google Analytics