Java multi-thread programming

Source: Internet
Author: User
Java multi-thread programming-Linux general technology-Linux programming and kernel information. For more information, see the following. Before the emergence of the Java language, the traditional programming language programs can only operate on a single task at the same time, with low efficiency. For example, a program often blocks when receiving data input, the program can continue to run only after the program obtains data. With the rapid development of the Internet, this situation is becoming more and more intolerable: if the network receives data blocking, the background program will be in the waiting state without any further operations, this kind of blocking is often encountered. At this time, the CPU resources are idle. How nice if you can process multiple tasks at the same time in the background program! The Java language, produced by Internet technology, solves this problem. multithreading is an important feature of Java. In a Java program, we can run multiple independent threads concurrently. For example, if we create a thread for data input and output, another thread is created to process other data in the background. If the input and output threads are blocked when receiving data, the data processing thread is still running. Multi-threaded programming greatly improves program execution efficiency and processing capability.


Thread Creation


We know that Java is an object-oriented programming language. To design and use Java programs is to design and use classes. Java provides us with Thread threads to create threads, the operation for creating a Thread is the same as that for creating an object of a common class, and a Thread is an instance object of the Thread class or its subclass. The following is a statement for creating and starting a thread:


Thread thread1 = new Thread (); file: // declare an object instance, that is, create a Thread;


Thread1.run (); file: // use the run () method in the Thread class to start the Thread;


In this example, we can use the Thread () constructor to create a Thread and start it. In fact, the start Thread is the run () method of the start Thread, and the run () method in the Thread class does not have any operation statements, so this Thread does not have any operation. To enable the thread to implement the predefined function, you must define your own run () method. In Java, two methods are usually used to define the run () method:


By defining a subclass of A Thread class, the run () method is rewritten in this subclass. The instance object of the Thread subclass is a Thread. Obviously, this Thread has its own Thread body run () method. The startup Thread starts the run () method that is rewritten in the subclass.


Use the Runnable interface to define the interface for the run () method. The so-called interfaces are very similar to classes and are mainly used to implement special functions, such as multiple inheritance functions of complex relationships. Here, we define a class that implements the Runnable () interface and define our own run () method in this class, call the Thread class constructor with the instance object of this class as the parameter to create a Thread.


After a thread is created, it is in STANDBY state. The activation (start) thread is the run () method of the startup thread, which is implemented by calling the start () method of the thread.


The following example illustrates how to create threads and start them using the above two methods:


// The Thread created through the subclass of the Thread class;


Class thread1 extends Thread


{File: // The run () method of the custom thread;


Public void run ()


{


System. out. println ("Thread1 is running... ");


}


}


File: // another thread created through the Runnable interface;


Class thread2 implements Runnable


{File: // The run () method of the custom thread;


Public void run ()


{


System. out. println ("Thread2 is running... ");


}


}


File: // main class of the program'


Class Multi_Thread file: // declare the main class;


{


Plubic static void mail (String args []) file: // declare the main method;


{


Thread1 threadone = new thread1 (); file: // use the subclass of the Thread class to create a Thread;


Thread threadtwo = new Thread (new thread2 (); file: // use the Runnable interface class to create a Thread;


Threadone. start (); threadtwo. start (); file: // strat () method to start the thread;


}


}


Run the program to check that the threads threadone and threadtwo use the CPU and are running in parallel. We can see that the run () method of the startup thread is implemented by calling the start () method of the thread (see the main class in the previous example), and the start () method is called to start the run () method of the thread () the method is different from the general call method. When a general method is called, the start () method must be returned after the general method is executed. After the run () method of the thread is started, start () after telling the system that the thread is ready to start the run () method, the system returns the start () method to execute the following statement that calls the start () method. In this case, run () the method may still be running. In this way, the thread starts and runs in parallel to implement multi-task operations.


Thread priority


For multi-threaded programs, the importance of each thread is different. For example, when multiple threads are waiting to obtain the CPU time, we usually need a thread with a higher priority to preemptible the CPU time for execution; another example is that when multiple threads are executed in turn, the priority determines the number of times a high-level thread receives a CPU and how long it takes. In this way, the task processing efficiency of a high-priority thread is higher.


In Java, the priority of threads ranges from 1 to 1 ~ 10 indicates that the priority is divided into 10 levels. The priority is set by calling the setPriority () method of the thread object. In the preceding example, the priority setting statement is:


Thread1 threadone = new thread1 (); file: // use the subclass of the Thread class to create a Thread;
Thread threadtwo = new Thread (new thread2 (); file: // use the Runnable interface class to create a Thread;


Threadone. setPriority (6); file: // sets the priority of threadone 6;


Threadtwo. setPriority (3); file: // sets the priority of threadtwo 3;


Threadone. start (); threadtwo. start (); file: // strat () method to start the thread;


In this way, threadone takes precedence over threadtwo execution and occupies more CPU time. In this example, the priority setting can be set after the thread is started to meet different priority requirements.


Thread (synchronous) Control


Data can be shared among multiple threads of a Java program. When a thread accesses shared data asynchronously, it is sometimes insecure or non-logical. For example, one thread is reading data at the same time and the other thread is processing data. When the data processing thread does not wait until the Data Reading thread finishes reading the data, it will process the data, the error processing result is inevitable. This is not in conflict with the Data Reading and Data Processing parallel multi-task. This means that the data processing thread cannot process the data that has not been read, however, other data can be processed.


If we adopt a multi-threaded synchronization control mechanism and wait until the first thread reads the data, the second thread can process the data and avoid errors. It can be seen that thread synchronization is a very important technology in multi-thread programming.


Before talking about thread synchronization control, we need to explain the following concepts:


1. Use the Java keyword synchonized to synchronize operations on shared data


In an object, the synchronized method is declared using synchonized. Java has a Synchronization Model-Monitor, which is responsible for managing the thread's access to the Synchronization Methods in the object. Its principle is: Assign the object a unique 'key'. When multiple threads enter the object, only the thread that obtains the object key can access the synchronization method. Other threads wait in the object until the thread uses the wait () method to discard the key, other threads waiting to seize the key can be executed only after the thread that grabs the key is obtained. threads without obtaining the key are still blocked and waiting in the object.
File: // one way to declare synchronization: Synchronize the method declaration


Class store


{


Public synchonized void store_in ()


{
....


}
Public synchonized void store_out (){


....}
}


2. Use the wait (), notify (), and notifyAll () Methods to send messages to achieve mutual connection between threads.


Multiple threads in the Java program implement interaction through messages. These methods enable message sending between threads. For example, to define the synchonized method of an object, only one thread can access the synchronization method of the object at the same time, and other threads are blocked. You can usually wake up one or all other threads using the Y () or notifyAll () method. The wait () method is used to block the thread and wait for other threads to wake up with Y.


An actual example is production and sales. The production unit places the product in the warehouse, and the Sales Unit extracts the product from the warehouse. In this process, A sales unit must have a product in the warehouse to pick up the goods. If there is no product in the warehouse, the sales unit must wait.


In the program, if we define a warehouse store class, the instance object of this class is equivalent to a warehouse. In the store class, we define two member Methods: store_in (), it is used to simulate the product manufacturer to add a product to the warehouse. The strore_out () method is used to simulate the seller to take the product from the warehouse. Then define two thread classes: customer class, where the run () method removes the product from the warehouse by calling store_out () in the warehouse class to simulate the seller; the run () method in the thread-type producer calls the store_in () method in the warehouse class to add products to the warehouse to simulate the product manufacturer. Create and start a thread in the main class to add a product to the repository or remove the product.


If the store_in () and store_out () methods in the warehouse class do not declare synchronization, this is a general multi-thread. We know that multithreading in a program is executed alternately and the running is unordered, in this way, the following problems may occur:


There is no product in the warehouse, and the seller is still patronizing and constantly 'taobao' the product, which is unavoidable in reality and is negative in the program; if the stroe_in () and store_out () methods in the repository class are declared to be synchronized, as shown in the preceding example, only one thread can access the Synchronization Methods in the repository object at the same time; that is, when a production thread accesses the declared synchronized store_in () method, other threads cannot access the store_out () Synchronization Method in the object, and of course cannot access the store_in () method. Wait until the thread calls the wait () method to discard the key and other threads have the opportunity to access the synchronization method.


This principle is also very understandable in practice. When the producer obtains the unique key of the warehouse, it adds the product to the warehouse. At this time, other sellers (customers can be one or more) it is impossible to obtain the key. Only when the producer adds the product to the end, the key is returned and the seller is notified. Different Sellers decide whether to enter the warehouse to pick up the product based on the order in which the key is obtained.
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.