Java Multithreading Examples (ii) _java

Source: Internet
Author: User
Tags garbage collection set background

This article to undertake a previous article "Java multithreaded Examples (i)."

Four. Java multi-thread blocking state and line program control system

Several specific types of Java blocking have been mentioned above. See below for the main methods that cause Java thread blocking.

1.join ()

join--lets one thread wait for another thread to complete before continuing. If the join () method of the B-thread is invoked in a thread-thread execution body, a thread is blocked until a B-thread is executed, and a can continue execution.

public class ThreadTest {public

 static void Main (string[] args) {

 myrunnable myrunnable = new myrunnable ();
 Thread thread = new Thread (myrunnable);

 for (int i = 0; i < i++) {System.out.println (
  thread.currentthread (). GetName () + "" + i);
  if (i = =) {
  thread.start ();
  try {
   thread.join ();//The main thread needs to wait for thread thread execution before continuing with the
  catch (Interruptedexception e) {
   E.printstacktrace ()
;

}}}} Class Myrunnable implements Runnable {

 @Override public
 void Run () {for
 (int i = 0; i < i++) {
   system.out.println (Thread.CurrentThread (). GetName () + "" + i);}}}

2.sleep ()

sleep--the current executing thread to suspend the specified time and into a blocking state. During the period of sleep, the thread is not in a ready state and therefore does not get an opportunity to execute. Even if no other executable thread is present in the system, the Threads in sleep () are not executed. So the sleep () method is often used to suspend thread execution.

As mentioned earlier, when the start () method of the newly created thread is invoked, the thread enters the ready state, and the CPU time slice may be executed at a later time, and if you want this new thread to execute immediately, call the original thread's sleep (1) directly.

public class ThreadTest {public

 static void Main (string[] args) {

 myrunnable myrunnable = new myrunnable ();
 Thread thread = new Thread (myrunnable);

 for (int i = 0; i < i++) {System.out.println (
  thread.currentthread (). GetName () + "" + i);
  if (i = =) {
  thread.start ();
  try {
   thread.sleep (1);///Make Thread must be able to immediately execute the
  catch (Interruptedexception e) {
   e.printstacktrace ();

class Myrunnable implements Runnable {

 @Override public
 Void Run ()}}}} for
 (int i = 0; i < i++) {System.out.println (
  thread.currentthread (). GetName () + "" + i);
 }
 }
}

Note: Sleep a millisecond is enough, because the CPU will not be idle, will switch to the new thread.

3. Background threads (Daemon thread)

Concept/Purpose: Background threading is primarily a service for other threads (which are relatively known as foreground threads), or "Daemon threads." such as garbage collection threads in the JVM.

Lifecycle: The life cycle of a background thread is associated with the foreground thread lifecycle. Mainly reflected in: when all foreground threads are in a dead state, the background thread automatically dies (this is understandable too, because the background thread exists to serve the foreground thread, and since all foreground threads are dead, what's left of it?). Great!!!).

Set Background thread: The Setdaemon (True) method that invokes the thread object can set the specified thread as a background thread.

public class ThreadTest {public

 static void Main (string[] args) {
 Thread mythread = new Mythread ();
 for (int i = 0; i < i++) {
  System.out.println ("main thread i =" + i);
  if (i = =) {
  Mythread.setdaemon (true);
  Mythread.start ();

}}} Class Mythread extends Thread {public

 void run () {(
 int i = 0; i < i++) {
  System.out.println (" i = "+ i");
  try {
  thread.sleep (1);
  } catch (Interruptedexception e) {
  //TODO auto-generated catch
  block E.printstacktrace ();}}}

Determines whether a thread is a background thread: the Isdeamon () method that invokes the thread object.

Note: The main thread defaults to the foreground thread, the child thread created in the foreground thread creation defaults to the foreground thread, and the thread created in the background thread defaults to the background thread. Calling the Setdeamon (true) method to set the foreground thread as a background thread needs to precede the start () method call. After the thread died the day before yesterday, the JVM notifies the background thread of death, but it takes a certain amount of time to respond from the receive command to the response.

4. Change the priority of the thread/setpriority ():

Each thread has a certain priority at execution time, and higher priority threads have more opportunity to execute. The default priority for each thread is the same as that of the thread that created it. The main thread defaults to a normal priority.

Set Thread Priority: setpriority (int prioritylevel). The parameter Prioritylevel range is between 1-10 and the following three static constant values are commonly used:

Max_priority:10

Min_priority:1

Norm_priority:5

Gets the thread priority: GetPriority ().

Note: Thread objects with higher thread priority only indicate that this thread has more execution opportunities than priority execution.

public class ThreadTest {public

 static void Main (string[] args) {
 Thread mythread = new Mythread ();
 for (int i = 0; i < i++) {
  System.out.println ("main thread i =" + i);
  if (i = =) {
  mythread.setpriority (thread.max_priority);
  Mythread.start ();

}}} Class Mythread extends Thread {public

 void run () {(
 int i = 0; i < i++) {
  System.out.println (" i = "+ i);}}}

5. Thread Concession: Yield ()

The basic role of yield () is already mentioned in the previous post, while the yield () method is also related to thread precedence, when a thread calls the Yiled () method from the run state to the ready state. The CPU from the Ready state thread queue will only select threads that have the same priority or higher precedence for the thread to execute.

public class ThreadTest {public

 static void Main (string[] args) {
 Thread myThread1 = new MyThread1 ();
 Thread myThread2 = new MyThread2 ();
 Mythread1.setpriority (thread.max_priority);
 Mythread2.setpriority (thread.min_priority);
 for (int i = 0; i < i++) {
  System.out.println ("main thread i =" + i);
  if (i = =) {
  mythread1.start ();
  Mythread2.start ();
  Thread.yield ();

}}} Class MyThread1 extends Thread {public

 void run () {(
 int i = 0; i < i++) {
  System.out.println ( "Mythread 1--i =" + i);

}} Class MyThread2 extends Thread {public

 void run () {(
 int i = 0; i < i++) {
  System.out.println ( "Mythread 2--i =" + i);}}

Series of articles:

Java Multithreading Example Explanation (i)
Java Multithreading Examples (ii)
Java Multithreading Examples (iii)

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.