Dark Horse programmer-java Basics-Multithreading 1

Source: Internet
Author: User
Tags instance method

---restore content starts---

Single-threaded programs have only one sequential flow, while multithreaded programs can include multiple sequential execution flows, and multiple sequential streams do not interfere with each other. Just like a single-threaded one that hires only a waiter's restaurant, he can do one thing after the other, and multi-threaded is a restaurant that employs multiple waiters who can do multiple things at the same time.

Java multithreaded Programming Knowledge: Create, start threads, control threads, and multi-threaded synchronization operations.

1. Overview:

A process refers to a program that is running. Each process execution has an execution order, which is an execution path, or an execution unit.

A thread is a control unit that can be executed independently in a process. Threads control the execution of a process. A process can run multiple different threads at the same time.

The difference between the two:

After a program runs at least one process, a process can contain one or more threads.

Each process requires the operating system to allocate a separate memory address space, while all threads in the same process work in the same address space. These threads can share the state and resources of the process.

2. Create and start a thread:

There are two ways of creating a thread:

1, inherit the Java.lang.Thread class.

2, realize runnable interface.

 

2.1 Inheriting the thread class to create a threading class:

The steps are as follows:

1. Define the subclass of the thread class, and override the run () method of the threads.

2. Create an instance of the child class of the thread class, that is, create the thread object.

3. Call the thread's Start method to start the thread.

1//define subclass of Thread Class 2 class Threadtext extends Thread {  3//    override Run () Method 4 public     void Run () 5     {6 for         (in t a = 0; a <10; A + +) 7         {8             System.out.println (CurrentThread (). GetName () + ":" + a);  9         }10     }11}12 public class Stratthread {All     public     static void Main (String args[])     {16//< c14/> creates an instance of the subclass of the thread class,         threadtext t = new Threadtext ();//        Call the thread's start () method to start the thread.         T.start (); 20         the//         main thread calls the object run () method of the user thread.         T.run ();     }24}

Why would you want to rewrite the run () method of the thread class?

The thread class defines a feature that is used to store the code that the thread is running, which is the run () method. The method body of the run () method represents the task that the thread needs to accomplish. Therefore, we also refer to the run () method as the thread execution body.

Why call the Start () method to start a thread instead of the run () method?

Because invoking the start () method to start a thread, the system treats the run () method as a thread-executing body, and if the run () method of the thread object is called directly, the thread object is treated as a normal object, and the Run () method is a common method, not a thread-executing body.

The start () and run () methods are called in lines 19th and 22nd, respectively, in the preceding code. The results of the run are as follows:

main:0thread-0:0main:1thread-0:1main:2thread-0:2main:3thread-0:3main:4thread-0:4main:5thread-0:5main:6thread-0 : 6main:7thread-0:7thread-0:8thread-0:9main:8main:9

By running the result you can see two threads running alternately: T and main thread (when running a Java program, the JVM first creates and starts the main thread, and the main thread runs from main ().) Therefore, when a subclass of the thread class is called to invoke the Start () method, the thread is started, and the Run () method is called only to let the main thread run the code in its run () method, and does not start a new thread.

Note: A local variable is a separate copy of each thread.

In the above procedure, the 8th line uses the two methods of the thread class:

> Static thread CurrentThread (): This method is a static method of the thread class that returns the currently executing thread object.

> String getName (): The method is an instance method of thread that returns the name of the thread that called the method.

2.2 Implementing the Runnable interface to create a thread class:

1. Define the implementation class for the Runnable interface and override the Run method of the interface.

2. Create an instance of the Runnable implementation class, and use this instance as the target of the thread to create the thread object, which is the true thread object.

3. Call the Start () method of the thread object to start the thread.

  

1//define the implementation class of the Runnable interface 2 class Runnabletext implements Runnable 3 {4//    override the Run method of the interface. 5 public     Void Run () 6     {7 for         (int a = 0; a <10; a + +) 8         {9             System.out.println (thread.currentth Read (). GetName () + ":" + a);         }11     }12}13 public class Threadtextrunnable {All public     static void Main (String args[])        create an instance of the Runnable implementation class         Runnabletext t = new Runnabletext (), and/         /        via the new Thread (Runnable target Creates a new thread, threads         = new Thread (t),         thread1 = new Thread (t), and//        boot thread.         Thread.Start ();         Thread1.start ();     }29}

Why pass an instance of the Runnable implementation class to the thread's constructor?

Because, the custom run () method belongs to an instance of the implementation class of the Runnable interface. Therefore, in order for a thread to specify the object's run () method, the object to which the run () method belongs must be clarified.

2.3 Differences between the two ways:

2.3.1 uses multithreading that implements the Runnable interface approach

1, the thread class just implements the Runnable interface. Therefore, you can inherit other classes as well.

2. In this way, multiple threads can share the same target object, so it is appropriate for more than one thread to handle the same sub-resource.

2.3.2 takes the form of multithreading that inherits the thread class

1. Because threads inherit the thread class, they cannot inherit from other parent classes.

3. The running state of a thread

When a thread is created and started, it is not started to go into execution state, nor is it always in the execution state. The lifecycle of a thread undergoes the following centralized state: New, ready, running, blocked, and dead five states.

3.1 New and Ready (Runnable) states:

When a program creates a thread with the new keyword, the thread is in a new state, and it is only allocated memory by the JVM.

When the thread object calls the start () method, the thread is in the ready state. The thread in this state is qualified for operation but does not have the right to run. How to have the right to run depends on the thread scheduler in the JVM.

3.2 Ready (Runnable), run (Running), and blocking (Blocked) states:

If the ready state obtains the run right, the thread execution body of the run () method starts executing, and the thread is running.

When a thread starts running, he cannot be in a running state (unless its thread is short enough to execute in an instant). So when other threads grab the CPU execution right, the running state is back in the ready state. However, when the running state of a thread occurs, it goes into a blocking state (discarding the resource that is being used, that is, not performing the qualification):

1, the thread calls the Sleep method. When the time of sleep is up, the thread goes into a ready state.

2. The thread attempted to obtain a synchronization monitor, but the synchronization monitor was being held by another thread.

3, the thread waits for a notification (notify, notifyall), that is, wait pending.

3.3 Thread Death (Dead)

When the thread ends, it is in the dead state:

1. The run () method execution completes and the thread ends normally.

2, thread exception.

3. Call the thread's Stop () method directly to end the thread.

Note: Do not call the start () method on a thread that is in a dead state, and the program can only call the start () method on a new state thread. It is also an error to call the start () method two times for a new state thread.

4. Control threads

4.1 Join thread

When a thread executes to the join () method of the B thread, the A thread waits, and when the B thread finishes executing, a is executed. That is, a thread waits for the B thread to terminate.

1//define the implementation class of the Runnable Interface 2 public class Jointext implements Runnable {  3//    rewrite Run () Method 4 public     void Run () 5
   
    {6 for         (int i = 0; I <=  ; + + i) 7             System.out.println (Thread.CurrentThread (). GetName () + "..." + i); 8     } 9 public     static void Main (String args[]) throws InterruptedException10     {one//        create runnable An instance of the interface implementation class         Jointext t = new Jointext ()  ;//        Create a new thread by thread (Runnable target). Thread         thread = new T Hread (t)  ;         thread1 = new Thread (t), +//        start thread,         Thread.Start (), and//Only thread        threads execute At the end, the main thread will execute downwards;         thread.join ();         System.out.println ("Thread1 thread will start");         Thread1.start (); 22     }23}
   

In the above program, the thread thread invokes the join () method. So thread threads such as main line routines are executed until the end, so the result of the run is as follows:

Thread-0 ... 0thread-0 ... 1thread-0 ... 2thread-0 ... 3thread-0 ... 4thread-0 ... 5thread-0 ... 6thread-0 ... 7thread-0 ... 8thread-0 ... 9thread-0 ... 10thread1 thread will start Thread-1 ... 0thread-1 ... 1thread-1 ... 2thread-1 ... 3thread-1 ... 4thread-1 ... 5thread-1 ... 6thread-1 ... 7thread-1 ... 8thread-1 ... 9thread-1 ... 10

The Join method has three overloaded forms:

void join (): Waits for the thread to terminate.

void join (Long Millis): The longest time to wait for the thread to middle finger is millis milliseconds.

The Void join (long millis, int Nanos) waits for the thread to terminate for a maximum of millis milliseconds + nanos nanoseconds.

 

4.2 Daemon threads (Background threads)

Daemon thread, the JVM's garbage collection mechanism is a typical background thread.

Call the Thread object Setdaemon (True) method to specify that the thread is set to a background thread. The method must be called at the start thread, otherwise the illegalthreadstateexception exception will be thrown.

Background Threading Features: If all foreground threads are dead, the background thread will die automatically.

1 public class Daemontext implements Runnable {  2 public     Void Run () 3     {4 for         (int i = 0; i <; I + +) 5         {6             System.out.println (Thread.CurrentThread (). GetName () + "..." +i); 7         } 8     } 9 public     static void Main (String args[]) Ten     {         daemontext t = new Daemontext ()  ;         thread thread = new Thread (t); 1 3//secondary        thread set to background thread         Thread.setdaemon (TRUE); +//        start background thread         Thread.Start ();         for (int i = 0; i <; i + +)             System.out.println (Thread.CurrentThread (). GetName () + "..." +i); 22
   }23//        program execution to this, the foreground thread ends. The//        background thread also ends with it.     }26}

Because thread threads are set up as background threads. Therefore, when the main thread finishes running, the JVM exits voluntarily, and the background thread is ended.

4.3 Thread Sleeps: Sleep

When the thread calls the sleep method into a blocking state, it does not get an execution opportunity within its sleep period, even if there are no other threads in the system until the time of sleep. Therefore, calling sleep allows the thread to pause temporarily.

4.4 Thread Concession: yield

Similar to sleep, the currently executing thread can be paused, but he will not let the thread go into a blocking state. Instead, the execution of the current thread is canceled, leaving the current thread in a ready state. is equivalent to having the system's thread scheduler reschedule.

4.5 Changing the priority of a thread

Each thread executes with a certain priority, the higher priority gets more running opportunities, and the lower priority gets less chance of running.

Thread provides the setpriority (int newpriority) and getpriority () methods to set and return the priority of the specified thread. Set the priority integers between 1~10, or you can use the three static constants of the thread class:

> max_priority: The value is 10

> min_priority: The value is 1

> norm_priority: The value is 5

---restore content ends---

---restore content starts---

Single-threaded programs have only one sequential flow, while multithreaded programs can include multiple sequential execution flows, and multiple sequential streams do not interfere with each other. Just like a single-threaded one that hires only a waiter's restaurant, he can do one thing after the other, and multi-threaded is a restaurant that employs multiple waiters who can do multiple things at the same time.

Java multithreaded Programming Knowledge: Create, start threads, control threads, and multi-threaded synchronization operations.

1. Overview:

A process refers to a program that is running. Each process execution has an execution order, which is an execution path, or an execution unit.

A thread is a control unit that can be executed independently in a process. Threads control the execution of a process. A process can run multiple different threads at the same time.

The difference between the two:

After a program runs at least one process, a process can contain one or more threads.

Each process requires the operating system to allocate a separate memory address space, while all threads in the same process work in the same address space. These threads can share the state and resources of the process.

2. Create and start a thread:

There are two ways of creating a thread:

1, inherit the Java.lang.Thread class.

2, realize runnable interface.

 

2.1 Inheriting the thread class to create a threading class:

The steps are as follows:

1. Define the subclass of the thread class, and override the run () method of the threads.

2. Create an instance of the child class of the thread class, that is, create the thread object.

3. Call the thread's Start method to start the thread.

1//define subclass of Thread Class 2 class Threadtext extends Thread {  3//    override Run () Method 4 public     void Run () 5     {6 for         (in t a = 0; a <10; A + +) 7         {8             System.out.println (CurrentThread (). GetName () + ":" + a);  9         }10     }11}12 public class Stratthread {All     public     static void Main (String args[])     {//
    creates an instance of the subclass of the thread class,         threadtext t = new Threadtext ();//        Call the thread's start () method to start the thread.         t.start ();         The//         main thread calls the object run () method of the user thread.         T.run ();     }24}

Why would you want to rewrite the run () method of the thread class?

The thread class defines a feature that is used to store the code that the thread is running, which is the run () method. The method body of the run () method represents the task that the thread needs to accomplish. Therefore, we also refer to the run () method as the thread execution body.

Why call the Start () method to start a thread instead of the run () method?

Because invoking the start () method to start a thread, the system treats the run () method as a thread-executing body, and if the run () method of the thread object is called directly, the thread object is treated as a normal object, and the Run () method is a common method, not a thread-executing body.

The start () and run () methods are called in lines 19th and 22nd, respectively, in the preceding code. The results of the run are as follows:

main:0thread-0:0main:1thread-0:1main:2thread-0:2main:3thread-0:3main:4thread-0:4main:5thread-0:5main:6thread-0 : 6main:7thread-0:7thread-0:8thread-0:9main:8main:9

By running the result you can see two threads running alternately: T and main thread (when running a Java program, the JVM first creates and starts the main thread, and the main thread runs from main ().) Therefore, when a subclass of the thread class is called to invoke the Start () method, the thread is started, and the Run () method is called only to let the main thread run the code in its run () method, and does not start a new thread.

Note: A local variable is a separate copy of each thread.

In the above procedure, the 8th line uses the two methods of the thread class:

> Static thread CurrentThread (): This method is a static method of the thread class that returns the currently executing thread object.

> String getName (): The method is an instance method of thread that returns the name of the thread that called the method.

2.2 Implementing the Runnable interface to create a thread class:

1. Define the implementation class for the Runnable interface and override the Run method of the interface.

2. Create an instance of the Runnable implementation class, and use this instance as the target of the thread to create the thread object, which is the true thread object.

3. Call the Start () method of the thread object to start the thread.

  

1//define the implementation class of the Runnable interface 2 class Runnabletext implements Runnable 3 {4//    override the Run method of the interface. 5 public     Void Run () 6     {7 for         (int a = 0; a <10; a + +) 8         {9             System.out.println (thread.currentth Read (). GetName () + ":" + a);         }11     }12}13 public class Threadtextrunnable {All public     static void Main (String args[])     {//        Create an instance of the Runnable implementation class         Runnabletext t = new Runnabletext ();         //        via New Thread (Runnable targe T) to create a new thread         . Threads = new Thread (t),         thread1 = new Thread (t), and//        start thread.         Thread.Start ();         Thread1.start ();     }29}

Why pass an instance of the Runnable implementation class to the thread's constructor?

Because, the custom run () method belongs to an instance of the implementation class of the Runnable interface. Therefore, in order for a thread to specify the object's run () method, the object to which the run () method belongs must be clarified.

2.3 Differences between the two ways:

2.3.1 uses multithreading that implements the Runnable interface approach

1, the thread class just implements the Runnable interface. Therefore, you can inherit other classes as well.

2. In this way, multiple threads can share the same target object, so it is appropriate for more than one thread to handle the same sub-resource.

2.3.2 takes the form of multithreading that inherits the thread class

1. Because threads inherit the thread class, they cannot inherit from other parent classes.

3. The running state of a thread

When a thread is created and started, it is not started to go into execution state, nor is it always in the execution state. The lifecycle of a thread undergoes the following centralized state: New, ready, running, blocked, and dead five states.

3.1 New and Ready (Runnable) states:

When a program creates a thread with the new keyword, the thread is in a new state, and it is only allocated memory by the JVM.

When the thread object calls the start () method, the thread is in the ready state. The thread in this state is qualified for operation but does not have the right to run. How to have the right to run depends on the thread scheduler in the JVM.

3.2 Ready (Runnable), run (Running), and blocking (Blocked) states:

If the ready state obtains the run right, the thread execution body of the run () method starts executing, and the thread is running.

When a thread starts running, he cannot be in a running state (unless its thread is short enough to execute in an instant). So when other threads grab the CPU execution right, the running state is back in the ready state. However, when the running state of a thread occurs, it goes into a blocking state (discarding the resource that is being used, that is, not performing the qualification):

1, the thread calls the Sleep method. When the time of sleep is up, the thread goes into a ready state.

2. The thread attempted to obtain a synchronization monitor, but the synchronization monitor was being held by another thread.

3, the thread waits for a notification (notify, notifyall), that is, wait pending.

3.3 Thread Death (Dead)

When the thread ends, it is in the dead state:

1. The run () method execution completes and the thread ends normally.

2, thread exception.

3. Call the thread's Stop () method directly to end the thread.

Note: Do not call the start () method on a thread that is in a dead state, and the program can only call the start () method on a new state thread. It is also an error to call the start () method two times for a new state thread.

4. Control threads

4.1 Join thread

When a thread executes to the join () method of the B thread, the A thread waits, and when the B thread finishes executing, a is executed. That is, a thread waits for the B thread to terminate.

1//define the implementation class of the Runnable Interface 2 public class Jointext implements Runnable {  3//    rewrite Run () Method 4 public     void Run () 5
   
    {6 for         (int i = 0; I <=  ; + + i) 7             System.out.println (Thread.CurrentThread (). GetName () + "..." + i); 8     } 9 public     static void Main (String args[]) throws InterruptedException10     {one//        create runnable An instance of the interface implementation class         Jointext t = new Jointext ()  ;//        Create a new thread by thread (Runnable target). Thread         thread = new T Hread (t)  ;         thread1 = new Thread (t), +//        start thread,         Thread.Start (), and//Only thread        threads execute At the end, the main thread will execute downwards;         thread.join ();         System.out.println ("Thread1 thread will start");         Thread1.start (); 22     }23}
   

In the above program, the thread thread invokes the join () method. So thread threads such as main line routines are executed until the end, so the result of the run is as follows:

Thread-0 ... 0thread-0 ... 1thread-0 ... 2thread-0 ... 3thread-0 ... 4thread-0 ... 5thread-0 ... 6thread-0 ... 7thread-0 ... 8thread-0 ... 9thread-0 ... 10thread1 thread will start Thread-1 ... 0thread-1 ... 1thread-1 ... 2thread-1 ... 3thread-1 ... 4thread-1 ... 5thread-1 ... 6thread-1 ... 7thread-1 ... 8thread-1 ... 9thread-1 ... 10

The Join method has three overloaded forms:

void join (): Waits for the thread to terminate.

void join (Long Millis): The longest time to wait for the thread to middle finger is millis milliseconds.

The Void join (long millis, int Nanos) waits for the thread to terminate for a maximum of millis milliseconds + nanos nanoseconds.

 

4.2 Daemon threads (Background threads)

Daemon thread, the JVM's garbage collection mechanism is a typical background thread.

Call the Thread object Setdaemon (True) method to specify that the thread is set to a background thread. The method must be called at the start thread, otherwise the illegalthreadstateexception exception will be thrown.

Background Threading Features: If all foreground threads are dead, the background thread will die automatically.

1 public class Daemontext implements Runnable {  2 public     Void Run () 3     {4 for         (int i = 0; i <; I + +) 5         {6             System.out.println (Thread.CurrentThread (). GetName () + "..." +i); 7         } 8     } 9 public     static void Main (String args[]) Ten     {         daemontext t = new Daemontext ()  ;         thread thread = new Thread (t); 1 3//secondary        thread set to background thread         Thread.setdaemon (TRUE); +//        start background thread         Thread.Start ();         for (int i = 0; i <; i + +)             System.out.println (Thread.CurrentThread (). GetName () + "..." +i); 22
   }23//        program execution to this, the foreground thread ends. The//        background thread also ends with it.     }26}

Because thread threads are set up as background threads. Therefore, when the main thread finishes running, the JVM exits voluntarily, and the background thread is ended.

4.3 Thread Sleeps: Sleep

When the thread calls the sleep method into a blocking state, it does not get an execution opportunity within its sleep period, even if there are no other threads in the system until the time of sleep. Therefore, calling sleep allows the thread to pause temporarily.

4.4 Thread Concession: yield

Similar to sleep, the currently executing thread can be paused, but he will not let the thread go into a blocking state. Instead, the execution of the current thread is canceled, leaving the current thread in a ready state. is equivalent to having the system's thread scheduler reschedule.

4.5 Changing the priority of a thread

Each thread executes with a certain priority, the higher priority gets more running opportunities, and the lower priority gets less chance of running.

Thread provides the setpriority (int newpriority) and getpriority () methods to set and return the priority of the specified thread. Set the priority integers between 1~10, or you can use the three static constants of the thread class:

> max_priority: The value is 10

> min_priority: The value is 1

> norm_priority: The value is 5

---restore content ends---

Dark Horse programmer-java Basics-Multithreading 1

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.