Java Multithreaded Programming Essentials

Source: Internet
Author: User
Tags terminates thread class thread stop

Java multithreaded Programming Essentials recognize thread and runnable

There are two ways to implement multithreading in Java: Inheriting the thread class or implementing the Runnable interface. Runnable is an interface, it is recommended to use the interface to generate the thread, because the interface can implement multiple inheritance, and runnable only a run method, is suitable for inheritance. You only have to inherit the thread when using thread, and the new instance comes out and the start () method is called to start a thread.

Thread Test = new Thread();Test.start();

When using runnable, you need to first implement an instance of Runnable, and then start the thread.

Test impelements Runnable;Test t = new Test();Thread test = new Thread(t);test.start();

Summary: Thread and runnable are 2 ways to implement Java Multi-threading, Runable is an interface, thread is a class, it is recommended to use Runable to implement Java multi-threading, regardless, eventually need to pass Thread.Start () To keep the thread in a running state.

Know the start and run of thread

1) Start: Starts the thread with the Start method, actually implements the multi-threaded operation, then executes the following code without waiting for the Run method body code to complete. By invoking the start () method of the thread class to start a thread, the thread is in a ready (operational) state and is not running, and once the CPU time slice is taken, the run () method is started, where the method run () is called the thread body, which contains the contents of the thread to be executed. This thread terminates when the Run method finishes running.

2) The Run:run () method is just a common method of the class, if you call the Run method directly, the program is still only the main thread of the threads, its program execution path is only one, or to execute sequentially, or wait for the Run method body to complete before you can continue to execute the following code, This will not achieve the purpose of writing threads.

Summary: Call the Start method to start the thread, and the Run method is just a normal method call to thread, or execute in the main thread.

Thread Status Description

Thread state from a large aspect, can be attributed to: the initial state, operational status, non-operational state and extinction state, the specific can be subdivided into 7 states, described as follows:

1) The implementation of the thread has two ways, one is to inherit the thread class, and the other is to implement the Runnable interface, but anyway, when we new thread instance, the thread enters the initial state;

2) When the object calls the start () method, it enters the operational state;

3) After entering the operational state, when the object is selected by the operating system, the CPU time slice will go into the running state;

4) After entering the state of operation, case is more, roughly the following situation:

After the. Run () method or the main () method ends, the thread enters the terminating state;

When a thread calls its own sleep () method or another thread's join () method, it goes into a blocking state (which stops the current thread, but does not release the resources it occupies). When sleep () ends or join () ends, the thread enters the operational state and continues to wait for the OS to allocate time slices;

When a thread has just entered the operational state (note that it is not yet running), discovering that the resource to be called is locked (synchroniza,lock), it will immediately enter the lock pool state and wait for the lock tag (at this point the lock pool may already have other threads waiting to acquire the lock tag, when they are in the queue State, On a first-come-first-served basis, once the thread obtains the lock tag, it goes to the operational state, waiting for the OS to allocate CPU time slices;

When a thread calls the Wait () method, it enters the waiting queue (which frees up all the resources it occupies, unlike the blocking state), which is not automatically awakened after it enters this state, and must rely on other threads to invoke the Notify () or Notifyall () method to be awakened (because Notify () Just wakes up a thread, but we are not sure which thread is specifically awakened, perhaps the thread we need to wake up is not able to wake up, so in practice it is generally used with the Notifyall () method to wake up some threads), and the thread wakes up to the lock pool and waits for the lock token.

When a thread calls the Stop method, the thread goes extinct, but because the stop method is unsafe and discouraged, you can implement the thread stop by using the conditions in the Run method.

Use of timer and timer tasks

A timer is a timer tool that is used to schedule a specified task in a background thread that can be executed once or periodically. Each timer object corresponds to a background thread that executes all timer tasks sequentially. If the time to complete a timer task is too long, it will "monopolize" the task execution thread of the timer, potentially delaying the execution of subsequent tasks. After the last reference to the timer object finishes and all the unhandled tasks have been completed, the task execution thread of the timer terminates normally (and becomes the garbage-collected object). TimerTask is an abstract class that implements the Runable interface, and its subclasses represent a task that can be scheduled by the timer.

1) A simple demo, let everyone to the timer, TimerTask use of perceptual understanding.

2) Description of common API functions for timer and TimerTask

The difference between the schedule and scheduleatfixedrate of the timer class is emphasized here. The difference between schedule and scheduleatfixedrate is that schedule is executed at a fixed relative interval, and if one execution is delayed, the execution time of the subsequent execution will be relatively delayed. While the scheduleatfixedrate is performed at an absolute interval, the delay of the subsequent execution will be shortened if one execution is delayed (Scheduleatfixedrate will also execute the elapsed time as a cycle). Schedule is focused on the stability of the time interval, while the scheduleatfixedrate focuses on the stability of the frequency of execution.

3) Termination of the timer

By default, the program stays running as long as a program's timer thread is running. Of course, you can terminate a timer thread in the following four ways:

A) Call the timer's Cancle method. You can call this method from anywhere in the program, even in a timer task's Run method;

b) Make the timer thread a daemon thread (you can use the new timer (true) to reach this point when you create the timer), so that when the program has only daemon threads, it will automatically terminate the operation;

c) When all the tasks related to the timer have been executed, delete all references to this timer object (NULL) so that the timer thread terminates;

d) Call the System.exit method to terminate the entire program (all threads).

Summary: Timers and TimerTask can be simply understood as the timer timer in triggering TimerTask task calls, usually using schedule and Scheduleatfixedrate methods to invoke TimerTask tasks, Cancle to terminate a task call. The timer is easy to use, it is more suitable to provide a lightweight timer function, but for time-sensitive task scheduling please use other methods to implement (as Javadoc said "Timer does not offered real-time guarantees:it schedules Tasks using the object.wait (long) method ").

Article reprinted from: Le Orange Valley Guild Http://www.lechenggu.com/bbs/topic/57ecce7c13c3986107ad92de

Java Multithreaded Programming Essentials

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.