Threading Issues in Java

Source: Internet
Author: User
Tags stack trace terminates thread class

Let's take a brief look at the content of the single thread today.

Threads are an important part of Java, sometimes referred to as lightweight processes, and are the smallest units of program execution flows. A thread is a single sequential control process in a program that runs multiple threads at the same time in a single program to accomplish different tasks, called multithreading.

The 3 elements that a computer program can perform are: CPU, program code, and accessible data. In the Java language, the mechanism of multithreading is achieved through the virtual CPU, can be visualized as, in a Java language within a virtual multi-computer, each computer corresponding to a thread, has its own CPU, can obtain the required code and data, so can perform the task independently, You can also share code and data with each other.

Java threads are implemented through the Java.lang.Thread class, which implements the function of the virtual CPU, can receive and process the code and data passed to it, and provides independent operation control functions.

Let's look at the source code for the thread class:

Then look at the source code of the Runable interface:

It can be seen that the thread class implements the Runnable interface, while in the thread class, there are some more critical properties, such as name, which represents a thread, and the name of the thread may be specified by a parameter in the constructor of the thread class. Priority indicates the thread's precedence (maximum value is 10, minimum value is 1, default is 5), daemon indicates whether the thread is a daemon thread, and target represents the task to perform. When we create a thread, one way is to do it through thread, and the second is to run () by implementing the Runable interface and implementing the only method defined in the interface. Each of these two methods has its own advantages and disadvantages: direct inheritance of the thread class: can no longer inherit from other classes, write simple, can directly manipulate the thread, using the Runable interface: The CPU, code and data can be separated to form a clear model, can also inherit from other classes, and maintain the consistency of the program style.

There are some methods in the thread class, I copied the csdn in seapeak007 blog content, I think the summary is good.

Method Summary
static int activecount ()
returns the number of active threads in the thread group for the current thread.
void checkAccess ()
determines whether the currently running thread has permission to modify the thread.
int countstackframes ()
is obsolete. The definition of the call depends on suspend (), but it has been objected to. In addition, the result of the call is never clear-reaching.
static Thread CurrentThread ()
returns a reference to the currently executing thread object.
void Destroy ()
is obsolete. The method was originally used to destroy the thread, but no cleanup was made. Any monitor it maintains will remain locked. However, this method is never implemented. Even if it is to be implemented, it is most likely to be deadlocked in suspend () mode. If the target thread is destroyed while maintaining a lock that protects critical system resources, no thread can access the resource again at any time. If another thread has attempted to lock the resource, a deadlock occurs. Such deadlocks often prove themselves to be "frozen" processes. For more information, see why disapprove of using Thread.stop, Thread.Suspend, and Thread.Resume?.
static void DumpStack ()
prints the stack trace of the current thread to the standard error stream.
static int Enumerate (thread[] tarray)
copies each active thread in the current thread's thread group and its subgroups into the specified array.
static map<thread,stacktraceelement[]> getallstacktraces ()
returns a map of the stack traces for all active threads.
ClassLoader Getcontextclassloader ()
returns the context ClassLoader for this thread.
static Thread.uncaughtexceptionhandler Getdefaultuncaughtexceptionhandler ()
returns the default handler that is called when the thread terminates abruptly because the exception was not caught.
long getId ()
returns the identifier of the thread.
String getName ()
returns the name of the thread.
int getpriority ()
returns the priority of the thread.
stacktraceelement[] Getstacktrace ()
returns an array of stack trace elements representing the stack dump of the thread.
thread.state getState ()
returns the state of the thread.
threadgroup Getthreadgroup ()
returns the thread group to which the thread belongs.
Thread.uncaughtexceptionhandler Getuncaughtexceptionhandler ()
returns the handler that is called when the thread terminates abruptly because the exception was not caught.
Static Boolean holdslock (Object obj)
returns True if and only if the monitor lock is persisted on the specified object by the front thread.
void interrupt ()
the thread is disconnected.
static Boolean interrupted ()
test if the front thread has been interrupted.
boolean isAlive ()
tests whether the thread is active.
boolean Isdaemon ()
tests whether the thread is a daemon thread.
boolean isinterrupted ()
tests whether the thread has been interrupted.
void Join ()
waits for the thread to terminate.
void Join (long Millis)
The maximum time to wait for the thread to terminate is Millis milliseconds.
void Join (long millis, int nanos)
The maximum time to wait for the thread to terminate is Millis milliseconds + Nanos nanoseconds.
void Resume ()
is obsolete. This method is only used with suspend (), but suspend () has been objected to because it has a deadlock tendency. For more information, see why disapprove of using Thread.stop, Thread.Suspend, and Thread.Resume?.
void Run ()
If the thread is constructed using a standalone Runnable run object, the Run method of the Runnable object is called, otherwise the method does nothing and returns.
void Setcontextclassloader (ClassLoader cl)
Sets the context ClassLoader for this thread.
void Setdaemon (Boolean on)
mark the thread as either a daemon thread or a user thread.
static void Setdefaultuncaughtexceptionhandler (Thread.uncaughtexceptionhandler eh)
sets the default handler that is called when a thread is abruptly terminated because it did not catch an exception, and no other handlers are defined for the thread.
void SetName (String name)
change the thread name so that it is the same as the parameter name.
void setpriority (int newpriority)
change the priority of the thread.
void Setuncaughtexceptionhandler (Thread.uncaughtexceptionhandler eh)
sets the handler that is called when the thread terminates abruptly because the exception was not caught.
static void sleep (long Millis)
lets the currently executing thread hibernate (suspends execution) within the specified number of milliseconds, which is affected by the accuracy and accuracy of the system timer and scheduler.
static void Sleep (long millis, int nanos)
allows the currently executing thread to hibernate (suspend execution) within the specified number of milliseconds plus the specified number of nanoseconds, which is affected by the accuracy and accuracy of the system timer and scheduler.
void Start ()
causes the thread to start executing, and the Java virtual machine calls the thread's Run method.
void Stop ()
is obsolete. This method has inherent insecurity. Terminating a thread with Thread.stop frees all monitors it has locked (as a natural consequence of unchecked threaddeath exceptions that propagate up the stack). If any objects previously protected by these monitors are in an inconsistent state, the corrupted object will be visible to other threads, which may cause arbitrary behavior. Many uses of stop should be replaced by code that modifies only certain variables to indicate that the target thread should stop running. The target thread should check the variable periodically, and if the variable indicates that it is going to stop running, return from its run method. If the target thread waits for a long time (for example, based on a condition variable), you should use the interrupt method to interrupt the wait. For more information, see why disapprove of using Thread.stop, Thread.Suspend, and Thread.Resume?.
void Stop (Throwable obj)
is obsolete. This method has inherent insecurity. For more information, see Stop (). The additional danger of this method is that it can be used to generate exceptions that the target thread is not prepared to handle (including checked exceptions that the thread is less likely to throw if the method is not available). For more information, see why disapprove of using Thread.stop, Thread.Suspend, and Thread.Resume?.
void suspend ()
is obsolete. The method has been objected to because of its inherent deadlock tendency. If the target thread is suspended and there is a lock on the monitor that secures the critical system resources, no thread can access the resource until the target thread restarts. If the thread that is restarting the target thread wants to lock the monitor before calling resume, a deadlock occurs. This type of deadlock usually proves itself to be a "frozen" process. For more information, see why disapprove of using Thread.stop, Thread.Suspend, and Thread.Resume?.
String toString ()
returns the string representation of the thread, including the thread name, priority, and thread group.
static void yield ()
pauses the currently executing thread object and executes other threads.

Next talk about the basic state of the thread. The state of the thread is divided into 4 types: Create (New), run (runable), Block (Blocked), and Die (Dead).

Let's talk about the implementation. When using new to create a thread, it is in the created state, and at this point the thread does nothing and then calls the thread's start () method to register a thread with the thread dispatcher (usually the JVM (Java Virtual machine) or the operating system), and this thread is all ready, Wait for the CPU time. The thread scheduler schedules different threads according to the scheduling policy, and the calling thread's run () method gives the registered threads the opportunity to execute, and the dispatched program enters the running (Running) state. When the thread's run () method finishes running, the thread is discarded and enters the dead (Dead) state. You cannot call the restart () method to restart a thread that is in a dead state, but you can call each method of a thread object that is in a dead state. If the thread is in the running (Running) state because I/O is blocked, waits for keyboard input, invokes the thread's Sleeo () method, calls the object's Wait () method, and so on, the thread enters a blocking (Blocked) state until the blocking causes are lifted. The thread scheduler sets the thread in the running (Running) to the Runable state based on the scheduling situation.

There are several ways to end a thread: 1. Let the thread run () method finish, the thread ends naturally (this method is best), 2. Ends the thread by polling and sharing the flag bit, 3. The thread throws an uncaught (Catch) to the exception or Erro, Terminates the thread by calling the interrupt method and catching the interruptedexception exception; 4. Using the thread pool, when the threads are not used, let it sleep and put it into the queue.

Threading Issues in Java

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.