java--multithreaded Programming

Source: Internet
Author: User
Tags stack trace switches thread class

Java multithreaded Programming

Java provides built-in support for multithreaded programming. A multithreaded function contains two or more parts that can run concurrently. Each part of the program is called a thread, and each thread defines a separate execution path.

Multithreading is a special form of multitasking. Multithreading requires less overhead than multitasking.

Here you define another term related to threading: process: A process consists of memory space allocated by the operating system and contains one or more threads. A thread cannot exist independently, it must be part of a process. A process runs until all non-waiting threads end up running.

Multithreading enables programmers to write very efficient programs to get the most out of the CPU, because the CPU's idle time is kept to a minimum.

Life Week of a thread

Threads pass through various stages of their life cycle. Shows the full life cycle of a thread.

    • new state: a newly generated thread starts its life cycle from the new state. It keeps this state until the program start this thread.

    • running state: when a new state thread is started, the thread becomes operational and a thread is considered to be starting to perform its task in this state

    • ready state: When a thread waits for another thread to perform a task, the thread goes into a ready state. The thread is re-switched to the running state when another thread sends a signal to the ready state's thread.

    • hibernation: The thread goes into hibernation from the running state because a thread has run out of time slices. When the time interval expires or the waiting event occurs, the state of the thread switches to the running state.

    • terminating state: a running state of a thread completes a task or other termination condition occurs, and the thread switches to the terminating state.

Priority of the thread

Each Java thread has a priority, which helps the operating system determine the order in which the threads are dispatched. The Java priority is within the range of min_priority (1) and max_priority (10). By default, each thread will be assigned a priority of norm_priority (5).

A thread with a higher priority is more important to the program, and the processor time should be allocated before a low-priority thread. However, thread precedence does not guarantee the order in which threads are executed, and is very dependent on the platform.

Create a thread

Java provides two ways to create a thread:

    • By implementing the Runnable interface;

    • By inheriting the thread class itself.

To create a thread by implementing the Runnable interface

The simplest way to create a thread is to create a class that implements the Runnable interface.

To implement Runnable, a class simply executes a method call to run (), declared as follows:

public void Run ()

You can override this method, it is important to understand that run () can call other methods, use other classes, and declare variables, just like the main thread.

After you have created a class that implements the Runnable interface, you can instantiate a thread object in the class.

Thread defines several construction methods, and this is what we often use:

Thread (Runnable threadob,string threadname);

Here, Threadob is an instance of the class that implements the Runnable interface, and ThreadName specifies the name of the new thread.

After the new thread is created, you call it's start () method before it runs.

void Start ();

Instance

Here is an instance of creating a thread and starting to make it execute:

  Create a new thread class newthread implements runnable {   thread t;    newthread ()  {      //  Create a second new thread        t = new thread (this,  "Demo thread");       system.out.println ("child thread: "  + t);       t.start (); //  start thread    }     //  second thread entry    public  void run ()  {      try {          for (int i = 5; i > 0; i--)  {             system.out.println ("child thread: "  +  i);            //  suspend thread         &nbSp;    thread.sleep (;         } )     } catch  (interruptedexception e)  {          system.out.println ("child interrupted.");      }     system.out.println ("Exiting child  Thread. ");    }} public class ThreadDemo {   public static  Void main (string args[])  {      new newthread ();  //   Create a new thread       try {          for (int i = 5; i > 0; i--)  {            system.out.println ("main thread: "  + i);            thread.sleep(         }      } catch);   (interruptedexception e)  {          System.out.println ("main thread interrupted.");       }      system.out.println ("Main thread  exiting. ");    }}

Compile the above program to run the following results:

Child Thread:thread[demo thread,5,main]main thread:5child thread:5child thread:4main thread:4child thread:3child Thr Ead:2main thread:3child thread:1exiting child Thread. Main thread:2main thread:1main Thread exiting.

To create a thread by inheriting thread

The second way to create a thread is to create a new class that inherits the thread class and then creates an instance of the class.

The inheriting class must override the run () method, which is the entry point for the new thread. It must also call the start () method to execute.

Instance
  Create thread class newthread extends thread {    by inheriting  Thread  Newthread ()  {      //  Create a second new thread        Super ("Demo thread");       system.out.println ("child thread: ")  + this);       start (); //  start thread    }     //  Second thread entry    public void run ()  {       try {         for (int i = 5;  i > 0; i--)  {             system.out.println ("child thread: "  + i);                              //  Let threads hibernate for a while              thread.sleep (;    )      }      } catch  (interruptedexception  e)  {         system.out.println ("Child  Interrupted. ");       }      system.out.println ("Exiting  Child thread. ");    }} public class ExtendThread {   public static  Void main (string args[])  {      new newthread ();  //   Create a new thread       try {          for (int i = 5; i > 0; i--)  {             system.out.println ("main thread: "  + i);             thread.sleep (;     )     }      } catch  (Interruptedexception e)  {         system.out.println ("Main thread  Interrupted. ");       }      system.out.println ("Main thread  exiting. ");    }}

Compile the above program to run the following results:

Child Thread:thread[demo thread,5,main]main thread:5child thread:5child thread:4main thread:4child thread:3child Thr Ead:2main thread:3child thread:1exiting child Thread. Main thread:2main thread:1main Thread exiting.
Thread method

The following table lists some important methods of the thread class:

Serial Number Method Description
1 public void Start ()
Causes the thread to start executing, and theJava virtual machine calls the thread's Run method.
2 public void Run ()
If the thread is constructed using a standalone Runnable run object, the Run method of the Runnable object is called, otherwise the method does nothing and returns.
3 Public final void SetName (String name)
Change the thread name so that it is the same as the parameter name.
4 Public final void SetPriority (Int. priority)
The priority of the thread to be rerouted.
5 Public final void Setdaemon (Boolean on)
Mark the thread as either a daemon thread or a user thread.
6 Public final void Join (long millisec)
The maximum time to wait for the thread to terminate is Millis milliseconds.
7 public void Interrupt ()
The thread is disconnected.
8 Public Final Boolean isAlive ()
Tests whether the thread is active.

Tests whether the thread is active. The above method is called by the thread object. The following method is a static method of the thread class.

Serial Number Method Description
1 public static void Yield ()
Pauses the currently executing thread object and executes other threads.
2 public static void sleep (long millisec)
Lets the currently executing thread hibernate (suspends execution) within the specified number of milliseconds, which is affected by the accuracy and accuracy of the system timer and scheduler.
3 public static Boolean Holdslock (Object x)
Returns true if and only if the monitor lock is persisted on the specified object by the front thread.
4 public static Thread CurrentThread ()
Returns a reference to the currently executing thread object.
5 public static void DumpStack ()
Prints the stack trace of the current thread to the standard error stream.
Instance

The following Threadclassdemo program demonstrates some of the methods of the thread class:

File name: displaymessage.java//Create thread public class DisplayMessage implements runnable{private String Messa by implementing Runnable interface   Ge   Public DisplayMessage (String message) {this.message = message;      public void Run () {while (true) {System.out.println (message); }   }}

  File name  : GuessANumber.java//  create thread public class  by inheritance  Thread  class Guessanumber extends thread{   private int number;   public  guessanumber (Int number)    {      this.number =  number;   }   public void run ()    {       int counter = 0;      int guess  = 0;      do      {           guess =  (int)   (math.random ()  * 100 +  1);           system.out.println (This.getName ()                          +  " guesses  " + guess);          counter++;       }while (Guess != number);       System.out.println ("** correct! "  + this.getname ()                         +  "  in  " + counter + "  guesses.** ");    }}

 

  File name  : threadclassdemo.javapublic class threadclassdemo{   public  static void main (String [] args)    {       runnable hello = new displaymessage ("Hello");       Thread thread1 = new thread (hello);       thread1.setdaemon ( true);       thread1.setname ("Hello");       System.out.println ("Starting hello thread ...");       thread1.start ();            Runnable bye = new  DisplayMessage ("Goodbye");       thread thread2 = new thread ( Bye);       thread2.setpriority (thread.min_priority);       thread2.setdaemon (TRUE);Nbsp;     system.out.println ("Starting goodbye thread ...");       thread2.start ();        system.out.println ("Starting  thread3 ");       thread thread3 = new guessanumber (       thread3.start ();      try       {         thread3.join ();       }catch (interruptedexception e)       {          system.out.println ("thread interrupted.");       }      system.out.println ("Starting  Thread4 ");       thread thread4 = new guessanumber (75);         &nbSp;       thread4.start ();       System.out.println ("main ()  is ending ...");    }}

The results of the operation are as follows, and the results are different for each run.

Starting Hello thread ... Starting Goodbye thread ... Hellohellohellohellohellohellohellohellohellostarting thread3 ... Hellohellostarting thread4 ... Hellohellomain () is ending ...

Several key concepts of threading:

In multithreaded programming, you need to understand the following concepts:

    • Thread synchronization

    • Inter-thread communication

    • Thread deadlock

    • Line programmed: Suspend, stop, and resume

Use of multithreading

The key to effective use of multithreading is to understand that programs are executed concurrently rather than serially. For example, there are two subsystems in the program that need to be executed concurrently, which requires multithreaded programming.

Through the use of multithreading, you can write a very efficient program. Note, however, that if you create too many threads, the efficiency of the program execution is actually reduced, not promoted.

Keep in mind that the context switching overhead is also important, if you create too many threads, the CPU spends more time switching the context than executing the program!

java--multithreaded Programming

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.