Java thread multithreading and usage analysis _java

Source: Internet
Author: User
Tags set time thread class ticket

The most comprehensive Java multithreaded usage resolution, if you do not have in-depth research on Java multithreaded mechanism, this article can help you to understand more thoroughly Java multithreading principle and use method.

1. Creating Threads

There are two ways to create threads in Java: Using the thread class and using the Runnable interface. You need to create a thread instance when using the Runnable interface. Therefore, whether you create a thread through the thread class or the Runnable interface, you must establish an instance of the thread class or its subclass. Thread constructor:

    1. public Thread ();
    2. Public Thread (Runnable target);
    3. Public Thread (String name);
    4. Public Thread (Runnable target, String name);
    5. Public Thread (Threadgroup Group, Runnable target);
    6. Public Thread (Threadgroup Group, String name);
    7. Public Thread (Threadgroup Group, Runnable Target, String name);
    8. Public Thread (Threadgroup Group, Runnable Target, String name, long stacksize);

Method One: Inherit the thread class overwrite run method

public class ThreadDemo1 {public
  static void Main (string[] args) {
   demo d = new demo ();
   D.start ();
   for (int i=0;i<60;i++) {
    System.out.println (Thread.CurrentThread (). GetName () +i);
 }}} Class Demo extends thread{public
  void Run () {for
   (int i=0;i<60;i++) {
    System.out.println ( Thread.CurrentThread (). GetName () +i);}}
 

Method Two:

public class ThreadDemo2 {public
 static void Main (string[] args) {
  Demo2 D =new Demo2 ();
  Thread t = new Thread (d);
  T.start ();
  for (int x=0;x<60;x++) {
   System.out.println (Thread.CurrentThread (). GetName () +x);
}}} Class Demo2 implements runnable{public
 void Run () {for
  (int x=0;x<60;x++) {
   System.out.println ( Thread.CurrentThread (). GetName () +x);}}

2. The life cycle of threads

As with people living in sickness and death, threads also experience starting (waiting), running, suspending, and stopping four of different states. These four states can be controlled by methods in the thread class. The thread class and the four state-related methods are given below.

Start thread
Publicvoid start ();
Publicvoid run ();
Suspend and wake up threads
Publicvoid resume (); Use not recommended
Publicvoid suspend (); Use not recommended
Publicstaticvoid sleep (long Millis);
Publicstaticvoid Sleep (long millis, int nanos);
Terminating a thread
Publicvoid Stop (); Use not recommended
Publicvoid interrupt ();
Get thread State
Publicboolean isAlive ();
Publicboolean isinterrupted ();
Publicstaticboolean interrupted ();
Join method
Publicvoid join () throws interruptedexception;

Instead of executing the code in the Run method immediately after it is established, the thread is in the waiting state. When a thread is in a waiting state, you can use the method of the thread class to set the thread's not various properties, such as the thread's priority (setpriority), the thread name (SetName), and the type of thread (Setdaemon).

When the Start method is called, the thread starts executing the code in the Run method. The thread enters the running state. You can determine whether a thread is running by using the IsAlive method of the thread class. When the thread is running, IsAlive returns True, and when IsAlive returns false, it is possible that the thread is either in a waiting state or in a stopped state. The following code shows a switch between three states where a thread is created, run, and stopped, and outputs the corresponding IsAlive return value.

Once the thread starts executing the Run method, it will go on to the Run method to complete the line Cheng exit. However, in the process of thread execution, two methods can be used to temporarily stop the thread from executing. These two methods are suspend and sleep. After you suspend a thread using suspend, you can wake the thread through the Resume method. With sleep, which causes the thread to hibernate, it can only be ready after the set time (after the thread hibernation is finished, threads do not necessarily execute immediately, just enter the ready state and wait for the system to dispatch).

There are two points to be aware of when using the Sleep method:

1. The sleep method has two overloaded forms, one of which can be set to not only milliseconds but also nanoseconds (1,000,000 nanoseconds equals 1 milliseconds). However, the Java virtual machines on most operating system platforms are not accurate to nanoseconds, so if you set a nanosecond for sleep, the Java virtual machine takes milliseconds closest to that value.

2. You must use the throws or try{when using the Sleep method ...} Catch{...}. Because the Run method cannot use throws, you can only use try{...} Catch{...}. During thread hibernation, sleep throws a Interruptedexception exception when the thread is disconnected using the interrupt method. The sleep method is defined as follows:

Publicstaticvoid sleep (Long Millis) throws Interruptedexception
Publicstaticvoid Sleep (long millis, int nanos) throws Interruptedexception

There are three ways to terminate the thread.

1. Use the exit flag to cause the thread to exit normally, that is, the thread terminates when the Run method completes.

2. Use the Stop method to force a thread to terminate (this method is not recommended because it can also occur unpredictable results, as with suspend, resume).

3. Use the interrupt method to disconnect threads.

1. Terminate thread with Exit flag

When the Run method finishes executing, the thread exits. But sometimes the run method is never going to end. such as using threads in a server-side program to listen for client requests, or other tasks that need to be cycled. In this case, you typically put these tasks in a loop, such as a while loop. If you want the loop to run forever, you can use the while (True) {...} To deal with. But the most straightforward way to get the while loop to exit under a certain condition is to set a Boolean flag and control whether the while loop exits by setting the flag to true or false. An example of terminating a thread with an exit flag is given below.

The function of the join method is to make the thread that executes asynchronously into synchronous execution. That is, when the start method of the thread instance is invoked, the method returns immediately, and if you need to use a value computed by this thread after calling the Start method, you must use the Join method. If you do not use the Join method, you cannot guarantee that the thread will run out when a statement after the Start method is executed. After the Join method is used, the program does not go down until the thread exits. The following code demonstrates the use of join.

3. Multithreading Security Issues

Problem reason: When multiple statements operate on the same thread to share data, one thread executes only a portion of the statement, not finished, and another thread participates in the execution, resulting in an error sharing the data.

WORKAROUND: A statement that shares data with multiple operations, allowing only one thread to perform, and other threads not executing during execution.

Sync code block:

public class ThreadDemo3 {public
 static void Main (string[] args) {
  Ticket T =new Ticket ();
  thread T1 = new Thread (t, "window One");
  Thread t2 = new Thread (t, "window Two");
  thread t3 = new Thread (t, "Window III");
  thread T4 = new Thread (t, "window Four");
  T1.start ();
  T2.start ();
  T3.start ();
  T4.start ();
 }
Class Ticket implements runnable{
 private int Ticket =400;
 public void Run () {while
  (true) {
   synchronized (new Object ()) {
    try {
     thread.sleep (1);
    } catch (Interruptedexception e) {
     //TODO auto-generated catch block
     e.printstacktrace ();
    }
    if (ticket<=0) break
     ;
    System.out.println (Thread.CurrentThread (). GetName () + "---sell" +ticket--);}}

Synchronization functions

public class ThreadDemo3 {public
 static void Main (string[] args) {
  Ticket T =new Ticket ();
  thread T1 = new Thread (t, "window One");
  Thread t2 = new Thread (t, "window Two");
  thread t3 = new Thread (t, "Window III");
  thread T4 = new Thread (t, "window Four");
  T1.start ();
  T2.start ();
  T3.start ();
  T4.start ();
 }
Class Ticket implements runnable{
 private int Ticket = 4000;
 Public synchronized void Saleticket () {
  if (ticket>0)
   System.out.println (Thread.CurrentThread (). GetName () + "SOLD" +ticket--);
 public void Run () {while
  (true) {
   saleticket ();
  }
 }
}

Sync function Lock is this static synchronization function lock is class

Communication between threads

public class ThreadDemo3 {public
 static void Main (string[] args) {
  class person{public
   String name;
   private String gender;
   public void Set (String name,string gender) {
    this.name =name;
    This.gender =gender;
   }
   public void Get () {
    System.out.println (this.name+ "..." +this.gender);
   }
  Final person P =new person ();
  New Thread (New Runnable () {public
   void run () {
    int x=0;
    while (true) {
     if (x==0) {
      p.set ("John", "Male");
     } else{
      P.set ("Lili", "NV");
     }
     x= (x+1)%2;}}
  ). Start ();
  New Thread (New Runnable () {public
   void run () {while
    (true) {
     p.get ();
    }}}
  ). Start ();
 }
*
Zhang Three .... Man
Zhang three .... Male
lili....nv
Lili ..... Man
Zhang three .... NV Lili ...
. Male
* * *

Modify the above code

public class ThreadDemo3 {public
  static void Main (string[] args) {
   class person{public
    String name;
    private String gender;
    public void Set (String name,string gender) {
     this.name =name;
     This.gender =gender;
    }
    public void Get () {
     System.out.println (this.name+ "..." +this.gender);
    }
   Final person P =new person ();
   New Thread (New Runnable () {public
    void run () {
     int x=0;
     while (true) {
      synchronized (p) {
       if (x==0) {
        p.set ("John", "Male");
       } else{
        P.set ("Lili", "NV");
       }
       x= (x+1)%2;}}}
   ). Start ();
   New Thread (New Runnable () {public
    void run () {while
     (true) {
      synchronized (p) {
       p.get ()}
     }}
    }
   }). Start ();
  }
 /*
 LILI....NV
 lili....nv
 lili....nv
 lili....nv
 lili....nv
 lili....nv
 Zhang three .... Man
 Zhang three .... Man
 Zhang three .... Man
 Zhang three .... Male
 * * *

Wait for wake mechanism

* * Thread waits for wake mechanism * Wait and wake must be the same lock/public class ThreadDemo3 {private static Boolean flags =false;
   public static void Main (string[] args) {class person{public String name;
   Private String gender;
    public void Set (String name,string gender) {this.name =name;
   This.gender =gender;
   public void Get () {System.out.println (this.name+ "..." +this.gender);
  } final person P =new person ();
    New Thread (New Runnable () {public void run () {int x=0;
       while (true) {synchronized (p) {if (flags) try {p.wait ();
       catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
      };
      if (x==0) {P.set ("John", "Male");
      }else{P.set ("Lili", "NV");
      } x= (x+1)%2;
      Flags =true;
     P.notifyall ();
  }}}). Start ();
  New Thread (New Runnable () {public void run () {while (true) {synchronized (p) {if (!flags) try {      P.wait ();
       catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
      };
      P.get ();
      Flags =false;
      P.notifyall ();
 }}}). Start ();
 }
}

Production consumption mechanism one

public class ThreadDemo4 {private static Boolean flags =false;
   public static void Main (string[] args) {class goods{private String name;
   private int num;
     public synchronized void Produce (String name) {if (flags) try {wait ();
     catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
    } this.name =name+ "number:" +num++;
    System.out.println ("produced ..." +this.name);
    Flags =true;
   Notifyall ();
     Public synchronized void consume () {if (!flags) try {wait ();
     catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
    System.out.println ("Consumption of the +name");
    Flags =false;
   Notifyall ();
  } Final Goods G =new goods ();
    New Thread (New Runnable () {public void run () {while (true) {g.produce ("commodity");
  }}). Start ();
 New Thread (New Runnable () {public void run () {while (true) {g.consume ();   }}). Start ();

 }
}

Production consumption mechanism 2

public class ThreadDemo4 {private static Boolean flags =false;
   public static void Main (string[] args) {class goods{private String name;
   private int num;
     public synchronized void Produce (String name) {while (flags) try {wait ();
     catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
    } this.name =name+ "number:" +num++;
    System.out.println (Thread.CurrentThread (). GetName () + "produced ..." +this.name);
    Flags =true;
   Notifyall ();
     Public synchronized void consume () {while (!flags) try {wait ();
     catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
    } System.out.println (Thread.CurrentThread (). GetName () + "Consumption of the" +name);
    Flags =false;
   Notifyall ();
  } Final Goods G =new goods ();
    New Thread (New Runnable () {public void run () {while (true) {g.produce ("commodity");
  }}, "producer number". Start (); New THread (New Runnable () {public void run () {while (true) {g.produce ("commodity");
  }}, "producer number Second". Start ();
    New Thread (New Runnable () {public void run () {while (true) {g.consume ();
  }}, "Consumer number". Start ();
    New Thread (New Runnable () {public void run () {while (true) {g.consume ();
 }}, "Consumer number Second". Start (); }/* Consumer number second consumption of the "Hu" Item No.: 48049 producer number one production .... Item Number: 48050 Consumer one consumption of the Hu Jintao item number: 48050 producer number one production .... Item Number: 48051 Consumer second consumption of the Hu Jintao item number: 48051 producer second production .... Item Number: 48052 Consumer second consumption of the Hu Jintao item number: 48052 producer number one production .... Item Number: 48053 Consumer one consumption of the Hu Jintao item number: 48053 producer number one production .... Item Number: 48054 Consumer second consumption of the Hu Jintao item number: 48054 producer second production ....

 Item Number: 48055 Consumer second consumption of the Hu Jintao item Number: 48055 * *

Above is the Java multithreading Data collation, follow-up continue to supplement the relevant knowledge, thank you for your support to this site!

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.