Java learning FAQ (4)-six States of a thread and an example of its security problems

Source: Internet
Author: User

Thread states

Threads can be in one of six states:

  • New
  • Runnable
  • Blocked
  • Waiting
  • Timed waiting
  • Terminated

Each of these States is explained in the sections that follow.

To determine the current states of a threads, simply call the getstate method.

 

New threads

When you create a thread with the new operator -- the thread is not yet running. This means that it is inNewState. When a thread is in the new State, the programe has not started executing code inside of it. A certain
Amount of bookkeeping needs to be done before a thread can run.

 

Runnable threads

Once you invoke the start method, the thread is in the runnable state. a runnable thread may or may not actually be running. it is up to the operating system to give the thread time to run. (The Java specification doen not call
This a separate State, though. A running thread is still in the runnable state .)

Once a thread is running, it doesn' t necessarily keep running. in fact, it is desirable if running threads occasionally pause so that other threads have a chance to run. the details of thread scheduling systems give each runnable
Thread a slice of time to perform its task. When that slice of time is exhausted, the operating system preempts the thread and gives another thread an opportunity to work.

All modern desktop and server operating systems use preemptive scheduling. however, small devices such as cell phones may use cooperating scheduling. in such a device, a thread loses control only when it callthe yield method,
Or it is blocked or waiting.

On a machine with multiple processors, each processor can run a thread, and you can Hava multiple threads run in parallel. of course, if there are more threads than processors, the scheduler still has to do time-slicing.

Always keep in mind that a runnable thread may or may ont be running at any given time. (This is why the States is called "runnable" and not "running .")

 

Blocked and waiting threads

When a thread is blocked ot waiting, it is temporarily inactive. It doesn' t execute any code and it consumes mininal resources. It is up to the thread schedto to reactivate it.

The details depend on how the inactive state was reached.

  • When the thread tries to acquire an intrinsic object lock (buy not a lock in the Java. util. concurrent Library) that is currently held by another thread, it becomes blocked. the thread becomes unblocked when all other threads
    Have relinquished the lock and the thread scheduler has allowed this thread to hold it.
  • When the thread waits for another thread to handle y the schedtion of a condition, it enters the waiting states. this happens by calling the object. wait or thread. join method, or by waiting for a lock or condition in the Java. util. concurrent
    Library. In practice, the differece between the blocked and waiting state is not significant.
  • Several methods have a timeout parameter. Calling them causes the thread to enter the timed waiting state. This state persists either until the timeout expired or the appropriate notification has been already ed. Methods
    Timeout include thread. Sleep and the timed versions of object. Wait, thread. Join, lock. trylock, and condition. await.

Terminated threads

A thread is terminated for one of two reasons:

  • It dies a natural death because the run method Exits normally.
  • It dies abruptly because an uncaught exception terminates the run method.

In particle, you can kill a thread by invoking its stop method. that method throws a threaddeath error object that kills the thread. however, the stop method is deprecated, And You shoshould never call is in yout own code.

The above content is taken from <Java core technology Volume I: Basic knowledge> (8th)

 

After a thread is started, it may not always be in the running state. When it is in the running state depends on the operating system. At a certain time point, it may be in a non-running state. be especially careful in program logic to prevent errors. for example, if you expect your thread to detect a specific point in time to execute an operation, your expectation may be faulty, because the thread is not running at this point in time, you cannot capture this point in time and finally miss the execution time.

In addition, do not confuse this point with the sleep call in the thread. After sleep is called in the thread, the thread enters another State rather than the runnable state. here we talk about the possibility that a thread may be in a non-running state when it is in the runnable state. when talking about the sleep method, it is worth noting that after the thread executes sleep (sleep) and automatically wakes up upon expiration and returns the runnable status, it may not be able to get the chance to run immediately. therefore, the time specified in the sleep method is the shortest time that the thread will not run,
The sleep method cannot guarantee that the thread will be executed immediately after its sleep expires.

 

The following is a simple and typical example to illustrate the possible security problems of multithreading:

Public void run () {While (true) {If (sum = 0) {sum ++ ;}......}......} sum is a variable shared by multiple threads.

 

When the above code is executed by multiple threads, when sum is 0, thread 1 executes the if judgment but does not execute sum ++, the operating system changes it into a non-running state and thread 2 enters the running state. At this time, sum is 0, and thread 1 and thread 2 executes sum ++ twice, this leads to security issues.

How can this problem be avoided? There are many methods. Here we use the synchronous code block to do it:

public void run() {while(true) {synchronized(this) {if(sum == 0) {sum++;}}......}......}

We use the if code block for synchronization, so that when thread 1 starts to execute the content in the code block but has not ended, other threads will not be able to enter this code block, that is, to ensureSynchronizedThis content only allows one thread to execute. When the thread is not finished, other threads cannot obtain the execution qualification, thus ensuring that the above security issues do not occur.

Pay attention to the operations when using multithreading.Shared content between threadsSecurity issues.

 

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.