Simple and intuitive - essentials of practical experience Java multi-threaded programming (2)

xiaoxiao2021-03-06  44

Using the Java programming language to implement thread Java programming languages ​​make multi-threads so simple and valid, so that some programmers say it is actually natural. Although the use of threads in Java is much easier than in other languages, there are still some concepts to be mastered. An important thing to remember is the main () function is also a thread and can be used for useful work. Programmers only need to create new threads when needing multiple threads. The Thread THREAD class is a specific class, ie not an abstract class, which encapsulates the behavior of threads. To create a thread, the programmer must create a new class exported from the Thread class. The programmer must override the thread's Run () function to complete useful work. The user does not call this function directly; but must call the Start () function of Thread (), the function calls Run (). The following code illustrates its usage: Create two new threads

Import java.util. *;

Class Timeprinter Extends Thread {

Int PauseTime;

String name;

Public TimePrinter (int x, string n) {

Pauseetime = x;

Name = n;

}

Public void run () {

While (true) {

Try {

System.out.println (Name ":" New

Date (System.currentTimeMillis ()));

Thread.sleep (Pauseetime);

} catch (exception e) {

System.out.println (e);

}

}

}

Static Public Void Main (String Args []) {

TimePrinter TP1 = New Timeprinter (1000, "Fast Guy");

TP1.START ();

TimePrinter TP2 = New Timeprinter (3000, "Slow Guy");

Tp2.start ();

}

}

In this example, we can see a simple program that displays the current time on the screen by two different time intervals (1 second and 3 seconds). This is done by creating two new threads, including main () total three threads. However, because sometimes the class to run as a thread may be part of a certain level, it is no longer possible to create threads according to this mechanism. Although any number of interfaces can be implemented in the same class, Java programming languages ​​only allow one class to have a parent class. At the same time, some programmers avoid export from the Thread class because it imparts classes. For this situation, you need a Runnable interface. Runnable Interface This interface has only one function, Run (), this function must be implemented by a class that implements this interface. However, it is slightly different from the previous example with the previous example. We can rewrite the previous example with the Runnable interface. (Different parts are expressed in black body.)

Create two new threads without strong plus class level

Import java.util. *;

Class Timeprinter Implements Runnable {

Int PauseTime;

String name;

Public TimePrinter (int x, string n) {

Pauseetime = x;

Name = n;

}

Public void run () {

While (true) {

Try {

System.out.println (Name ":" New

Date (system.currenttimemillis ())); thread.sleep (pausetime);

} catch (exception e) {

System.out.println (e);

}

}

}

Static Public Void Main (String Args []) {

Thread T1 = New Thread (New TimePrinter (1000, "Fast Guy"));

T1.Start ();

Thread T2 = New Thread (New TimePrinter (3000, "Slow Guy"));

T2.Start ();

}

}

Note that when you use the runnable interface, you cannot create the object you need and run it; you must run it within an instance of the Thread class. Many programmers prefer Runnable interface because inheritance from Thread class will impose class level. Synchronized keywords so far, what we see is only used in a very simple way. Only the smallest data stream, and no two threads accesses the same object. However, in most useful programs, there is usually a stream between threads. Try considering a financial application, there is an Account object, as shown in the following example: a number of activities in a bank

Public class account {

String Holdername;

Float Amount;

Public Account (String Name, Float AMT) {

Holdername = name;

Amount = AMT;

}

Public void deposit (float AMT) {

Amount = AMT;

}

Public void withdraw (float AMT) {

Amount - = AMT;

}

Public float checkbalance () {

Return Amount;

}

}

An error is lurked in this code sample. If this class is used for single-threaded applications, there will be no problems. However, in the case of multi-threaded applications, different threads may also access the same Account object, such as a joint account accessible to different ATMs. In this case, deposit and expenditure may occur in this way: a transaction is covered by another transaction. This situation will be catastrophic. However, Java programming languages ​​provide a simple mechanism to prevent this coverage. Each object has an associated lock at runtime. This lock can be obtained by adding a keyword Synchronized to a method. In this way, the revised Account object (as shown below) will not suffer such an error like data corruption: Synchronize multiple activities in a bank.

Public class account {

String Holdername;

Float Amount;

Public Account (String Name, Float AMT) {

Holdername = name;

Amount = AMT;

}

Public synchronized void deposit (float AMT) {

Amount = AMT;

}

Public synchronized void withdraw (float AMT) {

Amount - = AMT;

}

Public float checkbalance () {

Return Amount;

}

转载请注明原文地址:https://www.9cbs.com/read-68840.html

New Post(0)