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 {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 []) {TimePrinter TP1 = New TimePrinter (1000, "Fast Guy"); TP1.Start (); TimePrinter TP2 = New Timeprinter 3000, "Slow Guy"); TP2.Start ();}} In this case, we can see a simple program that displays both different time intervals (1 second and 3 seconds) on the screen. time. 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 hierarchical import java.util. *; Class Timeprinter Implements Runnable {Int PauseTime; String Name; Public Timeprinter (int x, string n) {PAUSETIME = 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 ();}} Please note that when using the runnable interface, you cannot directly create the object you need and run it; you must start from the Thread class Run it inside. 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 consideration of a financial application, there is an Account object, as shown in the following: A number of activities in a bank PUBLIC CLAS ACVOUNT {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;} public float checkbalance () {return amount;}} In this code Late an error. 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 the multiple activities in a bank; 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 This lock is required to operate when a function is running when a function is running, so another function is blocked. Please note that checkbalance () is not changed, it is strictly a read function. Because checkbalance () is not synchronous, any other method will not block it, and it does not block any other method, whether or not those methods are synchronized. The advanced multi-threaded support thread group threads in the Java programming language is individually created, but they can classify them into the thread group to facilitate debugging and monitoring. You can only associate it with a thread group while creating a thread. In programs that use a large number of threads, use thread group organization threads may be helpful. They can be considered as a directory and file structure on a computer. Inter-threaded information When the thread is waiting to wait for a condition before continuing execution, only the synchronized keyword is not enough. Although the Synchronized keyword blocks concurrently updated an object, it does not implement the thread. The Object class provides three functions for this: Wait (), Notify () and NotifyAll (). Take the global climate prediction procedure as an example. These programs are divided into many units in each loop by dividing the earth, and each unit is calculated until these values tend to stabilize, and then some data is exchanged between adjacent cells. Therefore, from essentially, each thread in each cycle must wait for all threads to complete their tasks to enter the next loop.
This model is called shielding synchronization, the following example illustrates this model: the shield synchronization public class BSync {int totalThreads; int currentThreads; public BSync (int x) {totalThreads = x; currentThreads = 0;} public synchronized void waitForAll () {currentThreads ; If (currentthreads Lock When a thread is busy accepting new tasks, it will never have a chance to complete any tasks, there will be live locks. This thread will eventually exceed the buffer and cause the program to crash. Imagine a secretary to enter a letter, but she has been busy answering the phone, so this letter will never be entered. Memory damage If you use the Synchronized keyword inefficient, you can avoid memory of this madness. Resources run out of certain system resources are limited, such as file descriptors. Multi-threaded programs may deplete resources because each thread may wish to have such resources. If the number of threads is quite large, or the number of candidates for a resource far exceeds the number of available resources, it is best to use the resource pool. One of the best examples is the database connection pool. As long as the thread needs to use a database connection, it takes one from the pool and returns it back to the pool. The resource pool is also called a repository. Debugging a large number of threads Sometimes a program is extremely difficult because there are a lot of threads running. In this case, the following may be sent to the field: public class probe () {} public void () {} public void run () {while (true) {thread [] x = new thread [100]; thread .Enumerate (x); for (int i = 0; i <100; i ) {thread t = x [i]; if (t == null) Break; else system.out.println (t.getname () "/ t" T.GetPriority () "/ t" t.isalive () "/ t" t.Isdaemon ());}}}}}}}}}}}}}}}} Change thread priority. Essentially, the thread priority is a number between 1 and 10, the larger the number, the more urgent task. The JVM standard first calls a higher priority thread and then calls a lower priority thread. However, this standard is randomly processed for a thread having the same priority. How to deal with these threads depends on the operating system strategy of the base layer. In some cases, the priority thread is running at time; in other cases, the thread will run until the end. Keep in mind that Java supports 10 priorities. The priority supported by the grassroots operating system may have much less, which will cause some confusion. Therefore, the priority can only be used as a very rough tool. The final control can be done by smartly using the Yield () function. Typically, do not rely on thread priority to control the status of the thread. Small junctions illustrate how to use threads in the Java program. A more important issue like a thread should be used on a large program depends on the hand of the hand. A way to determine if multiple threads in the application is to estimate the amount of code that can run in parallel. And remember the following: Using multithreading does not increase the capacity of the CPU. However, if the local thread implementation of JVM is implemented, different threads can run simultaneously on different processors (in the machine in multi-CPU), so that the multi-CPU machine is fully utilized. If the application is a computing intensive and is restricted by the CPU function, only multiple CPU machines can benefit from more threads.