`

4. multi-thread : thread status

阅读更多

转载自

  • A java thread is an execution context or a lightweight process. It is a single sequential flow of control within a program. Programmer may use java thread mechanism to execute multiple tasks at the same time.
  • Thread class and run() Method
    • Basic support for threads is in the java.lang.Thread class. It provides a thread API and all the generic behavior for threads. These behaviors include starting, sleeping, running, yielding, and having a priority.
    • The run() method gives a thread something to do. Its code should implement the thread's running behavior.
      There are two ways of creating a customized thread:
      • Sub classing java.lang.Thread and Overriding run() method.
      • Implementing the java.lang.Runnable Interface.

Thread Scheduling

  • When we say that threads are running concurrently, in practice it may not be so. On a computer with single CPU, threads actually run one at a time giving an illusion of concurrency.
  • The execution of multiple threads on a single CPU based on some algorithm is called thread scheduling.
  • Thread scheduler maintains a pool of all the ready-to-run threads. Based on fixed priority algorithm, it allocates free CPU to one of these threads.

 

The Life Cycle of a Thread 
The following diagram illustrates the various states that a Java thread can be in at any point during its life and which method calls cause a transition to another state.

 

status

 

  • Ready-to-run
    A thread starts its life cycle with a call to start(). For example
     MyThread aThread = new MyThread();
     aThread.start();
    
    A call to start() will not immediately start thread's execution but rather will move it to pool of threads waiting for their turn to be picked for execution. The thread scheduler picks one of the ready-to-run threads based on thread priorities.
  • Running
    The thread code is being actively executed by the processor. It runs until it is swapped out, becomes blocked, or voluntarily give up its turn with this static method
     Thread.yield();
    
    Please note that yield() is a static method. Even if it is called on any thread object, it causes the currently executing thread to give up the CPU.
  • Waiting
    A call to java.lang.Object's wait() method causes the current thread object to wait. The thread remains in "Waiting" state until some another thread invokes notify() or the notifyAll() method of this object. The current thread must own this object's monitor for calling the wait().
  • Sleeping
    Java thread may be forced to sleep (suspended) for some predefined time.
     Thread.sleep(milliseconds);
     Thread.sleep(milliseconds, nanoseconds);
    
    Please note that static method sleep() only guarantees that the thread will sleep for predefined time and be running some time after the predefined time has been elapsed.
    For example, a call to sleep(60) will cause the currently executing thread to sleep for 60 milliseconds. This thread will be in ready-to-run state after that. It will be in "Running" state only when the scheduler will pick it for execution. Thus we can only say that the thread will run some time after 60 milliseconds.
  • Blocked on I/O.
    A java thread may enter this state while waiting for data from the IO device. The thread will move to Ready-to-Run after I/O condition changes (such as reading a byte of data).
  • Blocked on Synchronization.
    A java thread may enter this state while waiting for object lock. The thread will move to Ready-to-Run when a lock is acquired.
  • Dead
    A java thread may enter this state when it is finished working. It may also enter this state if the thread is terminated by an unrecoverable error condition.

 

 

Thread Synchronization 
Problems may occur when two threads are trying to access/modify the same object. To prevent such problems, Java uses monitors and the synchronized keyword to control access to an object by a thread.

  • Monitor
    • Monitor is any class with synchronized code in it.
    • Monitor controls its client threads using, wait() and notify() ( or notifyAll() ) methods.
    • wait() and notify() methods must be called in synchronized code.
    • Monitor asks client threads to wait if it is unavailable.
    • Normally a call to wait() is placed in while loop. The condition of while loop generally tests the availability of monitor. After waiting, thread resumes execution from the point it left.
  • Synchronized code and Locks
    • Object lock
      Each Object has a lock. This lock can be controlled by at most one thread at time. Lock controls the access to the synchronized code.
    • When an executing thread encounters a synchronized statement, it goes in blocked state and waits until it acquires the object lock. After that, it executes the code block and then releases the lock. While the executing thread owns the lock, no other thread can acquire the lock. Thus the locks and synchronization mechanism ensures proper exceution of code in multiple threading.

 

Thread Priority 
A thread's priority is specified with an integer from 1 (the lowest) to 10 (the highest), Constants Thread.MIN_PRIORITY and Thread.MAX_PRIORITY can also be used. By default, the setPriority() method sets the thread priority to 5, which is the Thread.NORM_PRIORITY.

 
Thread aThread = Thread.currentThread();
int currentPriority;
currentPriority = aThread.getPriority();
aThread.setPriority( currentPriority + 1 );

Setting priorities may not always have the desired effect because prioritization schemes may be implemented differently on different platforms. However, if you cannot resist messing with priorities, use higher priorities for threads that frequently block (sleeping or waiting for I/O). Use medium to low-priority for CPU-intensive threads to avoid hogging the processor down.

 

 

Thread Deadlock 
In multiple threading, following problems may occur.

  • Deadlock or deadly embrace occurs when two or more threads are trying to gain control of the same object, and each one has a lock on another resource that they need in order to proceed.
  • For example, When thread A waiting for lock on Object P while holding the lock on Object Q and at the same time, thread B holding a lock on Object P and waiting for lock on Object Q, deadlock occurs.
  • Please note that if the thread is holding a lock and went to a sleeping state, it does not loose the lock. However, when thread goes in blocked state, it normally releases the lock. This eliminates the potential of deadlocking threads.
  • Java does not provide any mechanisms for detection or control of deadlock situations, so the programmer is responsible for avoiding them.

 

 

 

分享到:
评论

相关推荐

    EurekaLog_7.5.0.0_Enterprise

    4)....Fixed: ThreadID = 0 in StandardEurekaNotify 5)....Fixed: Dialog auto-close timer may reset without user input 6)....Fixed: Possible hang when quickly loading/unloading EurekaLog-enabled DLL 7).....

    MBAXP Modbus ActiveX Control

    The communication in each instance of MBAXP runs in its own thread. That means: Your program does not stop responding while waiting for Modbus transactions to finish. You can communicate with multiple...

    Sakemail

    (thanks to Don Higgins).19/12/971.4.1- Fixed a bug that send double ‘<‘ and ‘>‘ (ie. <<ser@dom.com>>) when the full user name is used. Check the new SMTP demo. Thanks to Serge Wagener for locate ...

    串口通讯控件

    - BaseTerm sample queue status dialog made non-modal and auto-refreshing. - Other minor presentational improvements to BaseTerm sample. - Corrected bugs which caused occasional crashes on port ...

    BURNINTEST--硬件检测工具

    Status ====== This is a shareware program. This means that you need to buy it if you would like to continue using it after the evaluation period. Installation ============ 1) Uninstall any previous ...

    python3.6.5参考手册 chm

    PEP 489: Multi-phase extension module initialization Other Language Changes New Modules typing zipapp Improved Modules argparse asyncio bz2 cgi cmath code collections collections.abc ...

    FastReport.v4.15 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版支持D4-XE5

    FastReport.v4.15 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版支持Delphi 4-XE5 and C++Builder 6-XE5. D2010以上版本(D14_D19)安装必读 delphi2010以上版本(D14_D19)使用者安装时,请将res\frccD14_...

    Debugging with GDB --2007年

    5.4 Stopping and starting multi-thread programs . . . . . . . . . . . . . 6 Examining the Stack . . . . . . . . . . . . . . . . . . . . . . 51 6.1 6.2 6.3 6.4 6.5 6.6 7 Stack frames . . . . . . . . . ...

    RH850F1L用户手册:软件

    1.3 Changes from the V850E2v3 Architecture ............................................................................4 CHAPTER 2 PROCESSOR MODEL ........................................................

    Java 9 Concurrency Cookbook - Second Edition

    At the end of the book, you will learn how to obtain information about the status of some of the most useful components of the Java Concurrency API and how to test concurrent applications using ...

    CE中文版-启点CE过NP中文.exe

    Added a statusbar to the hexview in memoryview Pointerscan for value scans now add the results to the overflow queue Opening a file and changing bytes do not change them to the file anymore (you need ...

    ModernGadgets_1.6.3.rmskin

    - Includes four GPU meters to monitor up to 4 discrete GPUs for multi-GPU setups - Able to be scaled to any size Network Meter - Local and global IP addresses - View your location based on your ...

    The Art of Linux Kernel Design

    Uses the Running Operation as the Main Thread Difficulty in understanding an operating system (OS) lies not in the technical aspects, but in the complex relationships inside the operating ...

    Visual C++ 编程资源大全(英文源码 其它)

    1,01.zip Output 显示所有的调试信息(5KB)<END><br>2,02.zip Some general debugging tips 一般的调试技巧(11KB)<END><br>3,03.zip Debugging ISAPI extension 调试ISAPI扩展(4KB)<END><br>4,04....

    Visual C++ 编程资源大全(英文源码 表单)

    1,01.zip MFC Extension Library MFC扩展界面库, 使用Visual C++ 6.0(15KB)<END><br>2,02.zip Visual Studio style UI Visual Studio风格的界面效果(15KB)<END><br>3,03.zip Internet Explorer 4 ...

    深入浅出mfc简体中文版

    * 第14 章 MFC 多緒程式設計(Multi-threaded Programming in MFC) / 745 從作業系統層面看執行緒/ 745 ㆔個觀念:模組、行程、執行緒/ 746 執行緒優先權(Priority) / 748 執行緒排程(Scheduling) / 751 Thread...

    Visual C++ 编程资源大全(英文源码 控件)

    1,01.zip 3D Text 显示3D文字(6KB)<END><br>2,02.zip A button within a button 按纽中的按纽(13KB)<END><br>3,03.zip Flat Owner Drawn Buttons 浮动的自画按纽(13KB)<END><br>4,04.zip Flat-...

Global site tag (gtag.js) - Google Analytics