Java multithreaded Programming Technology + code example

Source: Internet
Author: User
Tags generator int size thread class try catch

1. Java and his APIs can use concurrency. You can specify that the program contains different execution threads, each with its own method call stack and program counter, allowing threads to concurrently execute resources, such as shared memory, that can share the program's scope with other threads, known as multithreaded Programming (multithreading), at the core of C and C This ability is not available in the + + language, although they affect the design of Java.

2. The life cycle of threads

The life cycle of the new thread begins with the "new" state. Before the program starts the thread, the thread is always a "newborn" state, and after the program starts the thread, the thread enters the "run" state. A "running" state of a thread that is considered to be performing his task.

Before the program starts the thread, the thread is always in a "wait" state, and the thread reverts to the "Ready to run" state only when another thread notifies the waiting thread to continue executing.

A "Running" state can enter a "timed Wait" state, waiting for a specified period of time. When the time arrives or an event that the thread is waiting for occurs, the thread returns to a "running" state. Threads that are in a "timed wait" state and "wait" state cannot use it even if the processor is available. When a thread in a "running" state waits for another thread to perform a task, if it provides an optional waiting period, the thread enters a "timed wait" state. When another thread notifies the thread, or when the timed time period arrives (whichever is first satisfied), the thread returns to the "Run" state ... Another way to get a thread into a "timed wait" state is to sleep in a "running" state. The sleep thread maintains a specified time period (called a sleep time period) in the "Timed Wait" state, and it returns to the "Ready to run" state after that time. When a thread is not working to execute, it sleeps immediately. , example

When a thread attempts to perform a task and the task cannot be completed immediately, the thread goes from the run state to the blocked state. Cases Even if a processor is available, the blocked state thread cannot use it.

When a thread completes a task successfully, or (because of an error) terminates, the "run" thread enters the "terminate" state (sometimes called the "stagnant" state).

At the operating system level, Java's "running" state typically contains two separate states. The thread is in the ready state when the thread first transfers from the "new" state to the "Run" state. When the operating system gives the thread to the processor, the thread enters the "run" state from the "Ready" state (that is, execution), which is also called the "Dispatch thread". In most operating systems, each thread is given a small segment of processor time (the time slice) to perform the task. When the time slice arrives, the thread returns to the ready state, while the operating system gives the processor another thread.

3. Thread priority and thread scheduling

The Java thread Priority range is min_priority (constant 1) to max_priority (constant 10), and the default is Norm_priority (constant 5)

4. Create and Execute threads

Creating a thread referral implementation runnable interface

(1) runnable and Thread class

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 priv ATE final String taskname;

    

   The 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 would execute P ublic void Run () {try//put thread-for sleeptime amount of time {System.out.print

         F ("%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 to due

      Ion "); 

   //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 with runnable State

      Thread1.start ();//Invokes Task1 World抯 Run method

      Thread2.start ();//I  Nvokes Task2 World抯 Run Method

      Thread3.start ();//Invokes Task3-World抯 Run method

 

      System.out.println ("Tasks started, main Ends.\n ");

   } End main

}//End Class Runnabletester   

     

(2) Thread management and executor framework

.5 is the created thread that is displayed, but the referral uses the executor interface to manage the execution of the Runnable object. The Executor object creates and manages a set of threads for a Runnable object, which is the thread pool. The advantage is that executor objects can reuse existing threads, reducing the overhead of creating new threads for each task and improving performance.

The executor interface declares only one method named Execute, and receives a runnable argument. Executor will give each Runnable object passed to his execute method a thread that can be used in the thread pool. If no thread is available, Executor creates a new thread, or waits for a thread to become available, and assigns the thread to the Runnable object that is passed to the Execute method.

The Executorservice interface extends the executor interface.

Fig. 4.3:taskexecutor.java//Using a 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 (); The start threads and place in the runnable state Threadexecutor.execute (TASK1); Start Task1 Threadexecutor.execute (TASK2); Start Task2 Threadexecutor.execute (TASK3); 

      Start TASK3//Shut down the worker threads when their tasks complete threadexecutor.shutdown ();
   System.out.println ("Tasks started, main ends.\n");
}//End Main}//End Class Taskexecutor
 


5. Thread Synchronization

(1) thread synchronization (synchronization), which coordinates access to shared data by multiple concurrent threads. Synchronizing multiple threads in this way ensures that each thread that accesses a shared object can simultaneously exclude all other threads, known as "mutexes."

Another method is to use the built-in monitor in Java. Each object has a monitor and a monitor lock (or built-in lock). The monitor ensures that any time the monitor lock is held by the only thread with the greatest possible.

(2) Synchronous data sharing: performing atomic operations.

Adds integers to a array shared with the 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++)

      {

         s Haredsimplearray.add (i); Add an element to the shared array

      }//End with

   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 (one, 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.await 

           Termination ( 1, timeunit.minutes); if (tasksended) System.out.println (Sharedsimplearray); Print contents Else System.out.println ("Timed out while waiting for tasks to F"

      Inish. "); }//End Try catch (Interruptedexception ex) {System.out.println ("interrupted wh

      Ile wait for the tasks to finish. ");

 }//End Catch}//END main}//End Class Sharedarraytest


 

Fig.5.3:simplearray.java//Class that manages a integer array to is shared by multiple//threads with Synchroni

Zation.

 

Import Java.util.Random; public class Simplearray {private final int array[];//the shared integer array private int writeindex = 0;

 

   Index of next element to is 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.s 

      Leep (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 is 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.