Java multithreaded programming

Source: Internet
Author: User

1. Multithreading Basic Concepts

1.1 Processes and Threads

Process: A running instance of a computer program that contains instructions to be executed, has its own independent address space, contains program content and data, and the address space of different processes is isolated from each other; the process has various resource and state information, including open files, subprocess, and signal processing.

Threads: Represents the execution flow of a program, which is the basic unit of CPU scheduling execution, and threads have their own program counters, registers, stacks, and frames. Threads in the same process share the same address space while sharing memory and other resources owned by the process lock.

1.2 Java standard library provides process and thread-related APIs

The process mainly includes the Java.lang.Process class that represents the process and the Java.lang.ProcessBuilder class that creates the process;

The thread mainly consists of the Java.lang.Thread class that represents the thread, after the virtual machine is booted, usually only the Java class's Main method runs (the main thread), the runtime can create and start new threads (child threads), and a class of daemon threads (Damon thread). The daemon runs in the background, providing the services required to run the program. When all the threads running in the virtual machine are daemon threads, the virtual machine terminates running.

2. Thread class and Runnable interface

There are two ways to implement multithreading in Java, one is to inherit the thread class, one to implement the Runnable interface, and the thread class to be defined in the Java.lang package. A class can implement multi-threaded operations by inheriting the thread class and simultaneously covering the run () method in this class.

2.1 Creating Threads

Java defines two ways to create a thread:

(1) By inheriting the thread class, overriding the thread's run () method, placing the logic in which the threads run

(2) Instantiate the thread class by implementing the Runnable interface

For example, the use of these two methods: in practical applications, we often use multi-threading, such as the station ticketing system, the station's various ticket outlets equivalent to each thread. When we do this system may think of two ways to achieve, inherit the thread class or implement the Runnable interface, now look at the two ways to achieve the results.

(1) By inheriting the thread class

package com.threadtest;class mythread extends thread{         private int ticket = 10;    private String name;     public mythread (String name) {         this.name =name;    }        public  void run () {        for (int i =0;i<500;i++) {             if (this.ticket>0) {                 system.out.println ( This.name+ "Sell ticket---->" + (this.ticket--));             }        }    }}public class  Threaddemo {    &nbSp;  public static void main (String[] args)  {         mythread mt1= new mythread ("one Window");         mythread mt2= new mythread ("Window No. Second");         Mythread mt3= new mythread ("Window No. third");         mt1.start ();         mt2.start ();         Mt3.start ();     }}

Run results

One window selling ticket---->10 window sell ticket---->9 second window sell ticket---->10 window sell ticket---->8 window sell ticket---->7 One window sell ticket---->6 Third window sell ticket----> Window 101th Sell ticket---->5 window sell ticket---->4 window sell ticket---->3 window sell ticket---->2 window sell ticket---->1 second window sell ticket---->9 second window sell ticket----> 83rd window Sell ticket---->9 Third window sell ticket---->8 Third window sell ticket---->7 Third window sell ticket---->6 Third window sell ticket---->5 Third window sell---->4 Third window sell ticket----> 33rd window Sell ticket---->2 Third window sell ticket---->1 second window sell ticket---->7 second window sell ticket---->6 second window sell ticket---->5 second window sell---->4 second window sell ticket----> 32nd window Sell ticket---->2 Second ticket---->1

(2) by implementing the Runnable interface

Package com.threadtest;class mythread1 implements runnable{    private  int ticket =10;    private String name;     Public void run () {        for (int i =0;i<500;i+ +) {            if (this.ticket>0) {                 system.out.println ( Thread.CurrentThread (). GetName () + "sell ticket---->" + (this.ticket--);             }        }    }} Public class runnabledemo {        public static  void main (String[] args)  {        // todo  auto-generated method stub        //design of three threads           mythread1 mt = new mythread1 ();          thread t1 = new thread (MT, "one Window");          thread t2 = new thread (MT, "Window No. second");          thread t3 = new thread (MT, "Window No. third");          t1.start ();          t2.start ();          t3.start ();     }}
Run the results as follows window sell ticket---->10 Third window sell ticket---->9 Third window sell ticket---->7 Third window sell ticket---->5 Third window sell ticket---->4 Third window sell---->3 Third window sell ticket---- >2 Third window Sell ticket---->1 window sell ticket---->8 second window sell ticket---->6

Why is this happening? The teacher of Java training used to tell me this analogy:

Inherit the thread class, we are equivalent to take out three things namely three tickets to sell 10 of the task divided to three windows, they each do the various things sold each of the tickets to complete each task, because Mythread inherits the thread class, so in new Mythread creates three threads while creating three objects;

Achieve runnable, equivalent to take out a ticket to sell 10 of the task to three people to work together, new mythread equivalent to create a task, and then instantiate three thread, create three threads to arrange three windows to execute.

2.2 The difference between the thread class and the Runnable interface:

The thread class defines a number of methods whose derived classes can override these methods, in which only the run () method must be overridden. Of course, this approach also needs to be implemented when implementing the Runnable interface. In most cases, if you just want to rewrite the run () method without overriding his Thread method, you should use the Runnable interface. This is important because a subclass should not be created for the class (Thread) unless the programmer intends to modify or enhance the basic behavior of the class. In general, there are two main differences between using the thread class and the Runnable class:

(1) When using inheritance, it is primarily for the purpose of not having to re-develop, and having the characteristics of the parent class I need without knowing the implementation details. It also has a big drawback, that is, if our class has been inherited from a class (such as applets must inherit from the Applet Class), then the Thread class can no longer be inherited.
(2) Java can only be single-inheritance, so if you take the method of inheriting thread, then you may encounter problems in the future code refactoring, because you can not inherit other classes, in other aspects, there is not much difference between the two.
(3) Implement runnable is interface-oriented, extensibility and other aspects than extends thread good.
(4) using the Runnable interface to implement multithreading allows us to contain all the code in a class, which is advantageous to encapsulation, the disadvantage is that we can only use a set of code, if you want to create more than one thread and the individual threads to execute different code, you still have to create additional classes, if so, In most cases, it might not be as compact to inherit the Thread directly from multiple classes.

3. Thread Synchronization method

3.1 Synchronized Keywords

When multi-threading is used, it is sometimes necessary to reconcile more than two activities, a process known as synchronization (synchronization) implementation. There are two main reasons for synchronization: one is that more than two threads need access to the same shared resource, and that resource can only be accessed by one thread at a time, for example, two threads are not allowed to write to the same file at the same time, and the other is when one thread waits for an event caused by another thread. There must be some way to ensure that the previous thread is suspended before the event occurs, and that the waiting thread resumes execution after the event occurs.

All Java objects have a monitor object associated with the synchronzied that allows the thread to lock and unlock operations on the monitor object.

A, static method: The Java class corresponds to the Class class object associated with the monitor object.

B, instance method: The monitor object that the current object instance is associated with.

C, code block: The monitor object that the object in the code block declaration is associated with.

Note: When the lock is released, changes to the shared variable are written to the master, and when the lock is obtained, the contents of the CPU cache are invalidated. The compiler handles synchronized methods or blocks of code and does not move the code contained therein to the synchronized method or block of code, thereby avoiding problems caused by code rearrangement.

Example: The following methods GetNext () and getNextV2 () all obtain the monitor object associated with the current instance

public class synchronizedidgenerator{private int value = 0;     public synchronized int GetNext () {return value++;        } public int getNextV2 () {synchronized (this) {return value++; }     }  }

3.2 The Notify (), wait (), and Notifyall () methods of the object class

Consider the following scenario: Thread T executes in a synchronous method, requires access to resource R, and resource R is temporarily inaccessible, what does thread t do? If the thread t enters a polling loop that waits for a resource R, T locks the object and prevents other threads from accessing it. However, this is not a good method, it counteracts the programming advantage of multithreaded environment, the better solution is to let T temporarily give up control resources R, allow other threads allow, when the resource R can access, notify thread T, resume its execution. This approach relies on the thread communication methods provided by Java Notify (), wait (), and Notifyall (). The object class implements methods Notify (), wait (), and Notifyall (), so these methods are part of all objects that can only be called in synchronized content, and they are used as follows: Wait: Put the current thread in, In the object's wait pool, thread A calls the wait () method of the B object, thread A enters the B object's wait pool, and releases the lock for B. (here, thread A must hold the lock of B, so the code that is called must be under the synchronized modifier, or the java.lang.IllegalMonitorStateException exception will be thrown directly). Notify: This object waits for a thread in the pool, randomly picks a pool of locks placed in the object, and when a lock is released after the end of the thread, the threads in the lock pool can compete for the object's lock to get an execution opportunity. Notifyall: All the threads in the waiting pool in the object are placed in the lock pool.

This is a producer and consumer model that determines whether the buffer is full to consume and whether the buffer is empty to produce logic. It can be done with while and volatile, but it essentially causes the thread to be busy waiting, consuming CPU time, and impacting performance.

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.