Java Learning Materials-threads

Source: Internet
Author: User
Tags time in milliseconds

1, the concept of threading

1.1 programs, processes, and threads

Program: Program with static code, such as source program, target program.

Process: A process is a dynamic execution of a program. Normally we can see the system process in Windows Task Manager.

Thread: A thread is a smaller execution unit than a process. Each Java process has a main thread. Starting with main (), created by the Java Virtual machine. Other threads are created by the main thread.

1.2 Thread scheduling and prioritization

The priority of a thread is based on the importance of the thread, because during multiple threads execution, multiple threads are expected to occupy the same resource at the same time, and if the threads are not constrained by precedence, the machine will be in a deadlock state, that is, everyone wants the resource, but nobody gets it. That's the equivalent of what we usually say. A step back is a truth.

We can get and set the priority of the thread by calling methods GetPriority () and SetPriority () of the thread class, and the thread's priority bounds are between 1 (min_priority) and ten (max_priority), The default is 5 (norm_priority).

1.3 The State and life cycle of a thread

new state: The thread has been created but not yet executed (start () has not yet been called).

executable state: Threads can execute, although not necessarily executing. The CPU time may be assigned to the thread at any time, allowing it to execute.

running state: Get CPU resources, executing.

blocking state: The thread is not allocated CPU time, cannot be executed, may be blocking I/O, or is blocking the synchronization lock.

dead state: Normally the run () return causes the thread to die. Calling Stop () or destroy () also has the same effect, but is not recommended, the former produces an exception, the latter is forced to terminate, and the lock is not released.

The life cycle of a thread is divided into phases of generation, operation, waiting, termination, etc., and the transition conditions between phases and states are specific:

1.4 The most common method of controlling a thread's life cycle:

(1) Start (): The thread calls the method to start a thread so that it enters the ready queue from the new state, and once the CPU is acquired, it can start its own life cycle independently of the main thread that created it.

(2) Run (): All activities of the thread are defined by the thread body run () method, and the operation is performed after the thread object is called.

(3) Stop (): To force termination of execution of a thread, the thread class provides the last control-stop method of the Threads Stop ().

(4) Suspend (): In a Java language program, it is often necessary to suspend a thread without specifying how much time, at which point the Suspend () method provided by the thread class is available, and this method does not permanently stop the thread.

(5) Resume (): The suspended thread can be reactivated, and the reactivation method is the resume () method. Because suspend () contains an object lock, it makes the thread extremely prone to deadlock, where the locked object is permanently waiting for the resume () method, and the thread cannot be restarted by the paused thread using the start () method.

(6) isAlive (): A thread that has been started and not stopped is considered active and can be tested to determine if the thread is activated. The test method is IsAlive () and if the IsAlive () method returns True, the thread is active.

(7) Sleep (): The Sleep () method provided in the Java language thread class is simply a time to tell the thread how many milliseconds to rest, and if you want to defer execution of a thread, you can use the sleep () method. When the thread sleeps, the sleep () method does not occupy the system resources, and the other threads can still continue to work. Once the delay time is complete, the dormant thread is activated. The basic invocation form of the Sleep () method takes a parameter in milliseconds, which causes the thread to pause a specified delay time. When the delay is complete, the thread continues to work. Because the Java runtime employs a thread scheduling mechanism, it is generally possible to make the Java language program run faster by inserting a call to sleep () in the main loop of run (). Because a short delay can cause the interrupt of the sleep () end scheduling mechanism before the running thread is ready to enter hibernation, the forced scheduling mechanism aborts it and restarts it later so that the thread can do its own thing before it goes into hibernation.

(8) Wait () and notify (): When you write a Java language program that is divided into logical threads, you need to know clearly how these threads should communicate with each other. For example, the network data exchange program often needs to use sleep (), wait (), Suspend () and other methods to put a thread into a wait state, while another thread needs to use Notify (), Resume () and other methods will wait for thread activation.

2. Thread creation and startup

There are two ways to create a thread: By inheriting the thread class or by inheriting the Runnable interface.

The first type:

1) Define the field class to implement the Runnable interface.

2) Thread myThread = new Thread (target).

3) There is only one method in runnable: public void Run ().

4) Use the Runnable interface to provide data sharing for multiple threads.

5) In the Run method definition of the class that implements the Runnable interface, you can use the static method of the thread public static thread CurrentThread () to read a reference to the current thread.

The second type:

1) You can top a thread and rewrite its run method such as:

Class MyThread extends Thread {

public void Run () {...}

}

2) then generate the object of the class

MyThread MyThread = new MyThread (...)

3. thread synchronization and deadlock

3.1 Concept of the synchronization

First, we need to understand what thread synchronization is, because the CPU in the machine may have to handle many threads at the same time, but it is not the same thing if the kept executes a thread, and if the thread is going to take a day, then the other threads will not have a chance to execute. To solve this problem, we propose the concept of thread synchronization, in which thread synchronization is performed once per thread over a period of time. So how can all be executed once? is to constantly alternate execution. For example, there are 3 threads A, B, and C in the computer that need to be executed, assuming that execution starts from a, then stop letting B execute after a period of execution, and then if the time is up to B even if it is not finished, the position must be given to C to execute. Just keep looping until all the threads have finished executing. Of course, the same is true if multiple threads preempt a resource.

In the Java language, the concept of object mutex is introduced to ensure the integrity of the shared data operation, and the keyword synchronized to contact the object's mutex. When an object is synchronized decorated, it indicates that the object can only be accessed by one thread at any one time. We only need to propose a mechanism for the method, which is the Synchronized keyword, which consists of three usages: the Synchronized method, the synchronized block, and the synchronized class.

synchronized block: Declares the synchronized block with the Synchronized keyword. The syntax is as follows:

synchronized (syncobject) {

//Allow access to control code

}

Synchronized class: Declares a class by using the Synchronized keyword. The syntax is as follows:

Synchronized Class {

//The methods within the class are all synchronized

}

synchronized block is such a block of code, where the code must get the object SyncObject the lock side can execute, the specific mechanism described earlier. Because it can be arbitrary code block, and can arbitrarily specify the locked object, it is more flexible.

3.2 Thread Synchronization Examples

public class Testsync implements Runnable {

Timer timer = new timer ();


public static void Main (string[] args) {

Testsync test = new Testsync ();

Thread t1 = new thread (test);

Thread t2 = new Thread (test);

t1.setname ("T1");

t2.setname ("T2");

T1.start ();

T2.start ();

}


public void run () {

Timer.add (Thread.CurrentThread (). GetName ());

}

}


Class Timer {

private static int num = 0;


public synchronized void Add (String name) {//execute this method the current object is locked

//synchronized (this) {//Lock the current object

num++;

try {

Thread.Sleep (1);

} catch (Interruptedexception e) {

}

System.out.println (name + ", you are the first" + num + "thread using the timer");

// }

}

}

Operation Result:

T1, you're the 1th thread to use a timer.

T2, you're the 2nd thread to use a timer.

3.3 Thread Deadlock

thread deadlock is in the CPU of multiple threads at the same time want to use the same resource, so they all want to this resource, but all refused to let go, so in the end no one will get, so a kind of consumption down, so there is a deadlock state. In order to solve this situation, Java is going through various mechanisms to prevent the occurrence of this situation.

Sleep () method: When multiple threads preempt the resource, let the lower priority line enters upgradeable sleep for a while, that is, let it pause execution first, this method the biggest advantage is that it can be assumed that the length of time to set the thread temporarily, in Sleep () in the millisecond parameter.

Suspend () and Resume () methods: Two methods are used, Suspend () causes the thread to enter a blocking state, and does not automatically recover, it must be called by its corresponding resume () to enable the thread to re-enter the executable state. Typically, suspend () and resume () are used when waiting for the result of another thread: After the test finds that the result has not yet been generated, the thread is blocked and the other thread produces the result, calling resume () to restore it.

Yield () method: Yield () causes the thread to discard the current CPU time, but does not cause the thread to block, that is, the thread is still in an executable state, and the CPU time may be split again at any time. The effect of calling yield () is equivalent to the scheduler thinking that the thread has performed enough time to go to another thread.

Wait () and notify () (Notifyall ()) methods: Two methods are used, wait () causes the thread to enter a blocking state, it has two forms, one allows to specify a period of time in milliseconds as a parameter, and the other without parameters, the former when the corresponding Notify () is called or the thread re-enters the executable state when the specified time is exceeded, and the latter must be called by the corresponding notify ().

the Wait () and notify () methods are finally explained in two points:

(1) calling the Notify () method causes the unblocked thread to be randomly selected from the thread that was blocked by calling the wait () method of the object, and we cannot predict which thread will be selected, so be careful when programming and avoid problems with this uncertainty.

(2) In addition to notify (), there is also a method Notifyall () can also play a similar role, the only difference is that the call to the Notifyall () method will be called by the Wait () method of the object is blocked all the time all the threads unblocked. Of course, only the thread that gets the lock can go into the executable state.

Java Learning Materials-threads

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.