How to use Java to Write multi-threaded programs

Source: Internet
Author: User
I. Introduction1What is threadTo say a thread, you must first talk about the process, which is an instance of the program running. The thread can be seen as occupying the CPU time separately to execute the corresponding code. For early computers (such as DoS), threads are both processes and processes because they are single-threaded. Of course, a program can be multi-threaded. the threads in multiple threads seem to be doing their jobs in parallel, just like running multiple processors on one computer. When implementing multithreading on a multi-processor computer, they can indeed work in parallel, and using appropriate time-sharing policies can greatly improve the efficiency of program running. But there is a big difference between the two. The thread shares the address space. That is to say, multithreading can read the same address space at the same time and use this space for data exchange.2Why thread usage?Why is multithreading required? Anyone who has studied computer architecture knows this. Compared with multi-thread parallel execution, sequential execution can greatly improve the efficiency. For example, there are five threads thread1, thread2, thread3, thread4, thread5, And the consumed CPU time is, and 7, respectively. (Assuming that the CPU rotation cycle is 4 CPU times, and threads are independent of each other) It takes 19 CPU times to execute the task in sequence, and the time required for parallel execution must be less than 19 CPU times, the specific time depends on the threads that can be executed simultaneously. In very small-scale situations, if you are dealing with large-scale interactions between processes, the efficiency can be improved.3,JavaHow to Implement MultithreadingUnlike other languages, the concept of thread is important and deep-rooted in Java, because the thread system in Java is self-built by Java, java has a dedicated multi-threaded api library, so you can write a program that supports threads as quickly as possible. When using Java to create a thread, you can generate a Thread class or its subclass object, and send start () to this object () message (the program can send the START () message to any class object derived from the runnable interface), so that the program will continue to run until the run returns, at this point, the thread will die. In Java, threads have the following features: § in a program, the main thread is executed at the position of main. The execution location of other threads can be customized by the programmer. It is worth noting that the same applies to the applet.
§ Each thread executes its code in an ordered manner.
§ A thread executes its Code independently from other threads. If the threads interact with each other, a certain interaction mechanism must be used.
§ As mentioned earlier, the thread is in the shared address space. If the control is improper, a deadlock may occur here. Each thread is independent of each other, so local variables are completely independent and private to a thread. Therefore, during thread execution, each thread has its own local variable copy. Instance variable can be shared between threads, Which is why sharing data objects in Java is so useful, but the Java thread cannot arbitrarily access object variables: they need the permission to access data objects.2. Preparation knowledgeBefore analyzing this example, let's take a look at several concepts about threads, locks, semaphores, and Java APIs.LockFor most programs, they need to communicate with each other to complete the life cycle of the entire thread. The simplest way to achieve synchronization between threads is locking. To prevent the two associated threads from mistakenly accessing shared resources, the thread needs to lock and unlock the resources when accessing the resources. For the lock, there is a read lock, different synchronization policies such as write locks and read/write locks. In Java, all objects have locks. threads only need to use the synchronized keyword to obtain the lock. A method or synchronous code block can only be executed by one thread for a given class instance at any time. This is because the Code requires an object lock before execution.SemaphoresIn general, how can we control the few resources accessed by multiple threads? A very classic and simple method is to use the semaphore mechanism. The semaphore mechanism defines a semaphore, that is, the number of connections that can be provided. When a thread occupies a connection, the semaphore is reduced by one. When a thread is connected, add one to the semaphore. This method can be used to easily and effectively control thread synchronization issues, and it is particularly convenient to implement. See the following code: Class semaphore {
Private int count;
Public semaphore (INT count ){
This. Count = count;
}

Public synchronized void acquire (){
While (COUNT = 0 ){
Try {
Wait ();
} Catch (interruptedexception e ){
// Keep trying
}
}
Count --;
}

Public synchronized void release (){
Count ++;
Y (); // alert a thread that's blocking on this semaphore
}
}

Which APIs are provided in Java to compile multi-threaded programs? Here, only a few common methods and attribute values are listed.
Attribute value. There are three max_priority, min_priority, and norm_priority Methods: thread (); // create a thread.
Void run (); // For a class that inherits the runnable interface,
// He runs a thread, and does not do anything
Void setpriority (INT newpriority); // sets the priority.
Void start (); // run a program
Void sleep (long millis); // The thread sleeps in millis milliseconds.
Static void yield (); // temporary pause a program to run in other threads3. program example  Example 1,Let's take a look at the example below. The process of obtaining the money is to enter the password, and then determine the amount to be obtained. If the obtained amount is less than or equal to the amount that can be retrieved, withdraw returns true, then the ATM pays for the money, and then prints the list; otherwise, false is returned and the list is printed. For example, public class automatedtellermachine extends teller {
Public void withdraw (float amount ){
Account A = getaccount ();
If (A. Deduct (amount ))
Dispense (amount );
Printreceipt ();
}
}

Public class account {
Private float total;
Public Boolean deduct (float t ){
If (T <= total ){
Total-= T;
Return true;
}
Return false;
}
}

In this example, we assume that the same account can get money from different places, at the same time, in different places, by the wife and husband, the wife has entered the maximum amount on the account, and the husband is the same. If the wife has obtained the true return value after the input, but the value of the husband's thread has not been updated, in this way, the husband can also get the return value of true, which leads to a problem! How can this problem be solved? Java provides a control mechanism to ensure the atomicity of deduct operations, that is, the key word synchronized. You can solve this problem by adding synchronized to the Account's deduct method.Example 2,Here we use the most typical example of multithreading, producer and consumer issues. In this example, we define three classes: producer, consumer, and warehouse. During the whole life cycle of the program, the producer randomly creates a product and stores it in the warehouse, the consumer also immediately extracts the product from the warehouse. Import exception. producerconsumerexception;

/**
* Consumer. Java
* Consumer
* By: Jiabo
* Date: Mar 21,200 4
* Time: 2:47:58
*/
Public class Consumer extends thread {

Private warehouse;
Private string ID;

Public consumer (warehouse, string ID ){
This. Warehouse = warehouse;
This. ID = ID;
}

Public void run (){

Int TMP = (INT) math. Random () * 10;

Try {
Warehouse. Get (TMP );
System. Out. println ("Consumer #" + this. ID + "get" + TMP );
} Catch (producerconsumerexception e ){
E. printstacktrace ();
}

Try {
Sleep (INT) (math. Random () * 100 ));
} Catch (interruptedexception e ){
E. printstacktrace ();
}
}
}

In this class, it is worth noting that try-catch must be used in the run method, because it is possible for a consumer to retrieve something from the warehouse, such as the insufficient reserves in the warehouse, the same is true for consumers, except that the exception changes to warehouse full. Import exception .*;

/**
* Producer. Java
* Producer
* By: Jiabo
* Date: Mar 21,200 4
* Time: 2:47:45
*/
Public class producer extends thread {

Private warehouse;
Private string ID;

Public producer (warehouse, string ID ){
This. Warehouse = warehouse;
This. ID = ID;
}

Public void run (){

Int TMP = (INT) math. Random () * 10;

If (TMP! = 0 ){
Try {
Warehouse. Put (TMP );
System. Out. println ("Consumer #" + this. ID + "put" + TMP );
} Catch (producerconsumerexception e ){
E. printstacktrace ();
}
}

Try {
Sleep (INT) (math. Random () * 100 ));
} Catch (interruptedexception e ){
E. printstacktrace ();
}
}
}

The most important part is in the warehouse class. To ensure the atomicity of the get set, the synchronized keyword is used here and an exception that may run out is thrown during the operation. Import exception .*;

/**
* Warehouse
* By: Jiabo
* Date: Mar 21,200 4
* Time: 2:48:10
*/
Public class warehouse {

// Max capability of the warehouse
Private int Max;
Private int contents;

// Init with max capacity
Public warehouse (INT max ){
This. max = max;
This. Contents = 0;
}

Public synchronized void get (INT amount) throws producerconsumerexception {

// The amount you want to get is bigger than the contends that the warehouse stores
If (amount> This. Contents ){
Throw new notenoughgoodsexception ();
}

Amount-= contents;
}

Public synchronized void put (INT amount) throws producerconsumerexception {

// The amount you want to put is out of the capability of the warehouse
If (amount> (this. Max-This. Contents )){
Throw new warehousefullexception ();
} Else if (this. Contents = 0 ){
// Warehouse is empty
Throw new warehouseemptyexception ();
}

Amount + = contents;
}
}

 

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.