Java multithreaded Walkthrough

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

There are two ways to create threads in Java: Using the thread class and using the Runnable interface. A thread instance needs to be established when using the Runnable interface. Therefore, regardless of whether a thread is established either through the thread class or the Runnable interface, an instance of the thread class or its subclasses must be established. Thread constructor:

    • public Thread ();
    • Public Thread (Runnable target);
    • Public Thread (String name);
    • Public Thread (Runnable target, String name);
    • Public Thread (Threadgroup Group, Runnable target);
    • Public Thread (Threadgroup Group, String name);
    • Public Thread (Threadgroup Group, Runnable Target, String name);
    • Public Thread (Threadgroup Group, Runnable Target, String name, long stackSize);

Method One: Inherit the thread class override the Run method

Public class ThreadDemo1 {     public static void Main (string[] args) {      < Span style= "Font-family:tahoma;" > 
  demo d = new Demo ();     
    D.start ();   & nbsp     
for (int i=0;i<60;i++) {            
System.out.println (Thread.CurrentThread (). GetName () +i)   
      }   < Span style= "Font-family:tahoma;" > 
}
}&NBSP;
  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. Thread Life cycle

As with people, threads also have to go through four different states of starting (waiting), running, suspending, and stopping. These four states can be controlled through the methods in the thread class. The thread class and the four state-related methods are given below.

    • Start thread
    • Publicvoid start ();
    • Publicvoid run ();
    • Suspending and waking threads
    • Publicvoid resume (); Do not recommend using
    • Publicvoid suspend (); Do not recommend using
    • Publicstaticvoid sleep (long Millis);
    • Publicstaticvoid Sleep (long millis, int nanos);
    • Terminating a thread
    • Publicvoid Stop (); Do not recommend using
    • Publicvoid interrupt ();
    • Get Thread Status
    • Publicboolean isAlive ();
    • Publicboolean isinterrupted ();
    • Publicstaticboolean interrupted ();
    • Join method
    • Publicvoid join () throws interruptedexception;

The thread does not immediately execute the code in the Run method after it is established, but is in a wait state. When a thread is in a wait state, it is possible to set threads with different properties, such as thread priority (setpriority), thread name (setName), and thread type (Setdaemon), by means of the thread class.

When the Start method is called, the thread starts executing the code in the Run method. The thread goes into a 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, the thread may be in a wait state or it may be in a stopped state. The following code shows the switch between the creation, running, and stopping of three states for a thread, and outputs the corresponding IsAlive return value.

Once the thread starts executing the Run method, it will continue until this run method executes the line friend exits. However, in the course of thread execution, there are two ways to make threads temporarily stop executing. These two methods are suspend and sleep. After you use suspend to suspend a thread, you can wake the thread through the Resume method. While sleep causes a thread to hibernate, the thread is ready only after a set time (the thread does not necessarily execute immediately after the end of the threads hibernation, but is in a ready state, waiting for the system to dispatch).

There are two points to note when using the Sleep method:

1. The sleep method has two overloaded forms, where one of the overloaded forms can be set not only in milliseconds, but also in 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 the nanosecond to sleep, the Java virtual machine will take the milliseconds closest to this value.

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

    • Public Static void Sleep (long millis) throws interruptedexception
    • Public Static void Sleep (long Millis, int nanos) Throws interruptedexception

There are three ways to make a terminating 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 forcibly terminate the thread (this method is not recommended because stop and suspend, resume, can also cause unpredictable results).

3. Use the interrupt method to break the thread.

1. Terminating a thread with an exit flag

When the Run method finishes executing, the thread exits. But sometimes the run method is never finished. Use threads to listen for client requests in a server-side program, or other tasks that require cyclic processing. In this case, it is common to place these tasks in a loop, such as a while loop. If you want the loop to run forever, you can use while (True) {...} To deal with. However, the most straightforward way to make a while loop exit under a particular condition is to set a Boolean flag and control whether the while loop exits by setting this 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 called, the method returns immediately, and if you need to use a value computed by this thread after the Start method is called, you must use the Join method. If you do not use the Join method, you cannot guarantee that the thread will execute when it executes to a statement that follows the Start method. After using the Join method, the program will not execute until the thread exits. The following code demonstrates the use of join.



3. Multithreading Security Issues

Cause: When multiple statements are working on the same thread to share data, one thread executes only a portion of the multiple statements, does not finish, and another thread participates in the execution, causing the error to share the data.

WORKAROUND: A statement that shares data on multiple operations can only be executed by one thread, and other threads do not execute during execution.

Synchronizing code blocks:

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 three");
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 three");
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 ();
}    }}

Synchronous function Lock is this static sync function lock is class
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 ("Zhang San", "male");
}else{ 
P.set ("Lili", "NV");

x= (x+1)%2;
}
}
}). Start (); 
New Thread (New Runnable () { 
public void Run () {
while (true) {
P.get ();
}
}
}). Start ();
}}

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 ("Zhang San", "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 (); } }

Original address Java multithreading http://techfoxbbs.com/

Java multithreaded Walkthrough

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.