Java线程可以有开始,结束和序列,这是什么意思?
2 回答
我认为这意味着一个线程执行一系列动作。老实说,它非常糟糕地表达了这个概念。
换句话说:
- 您创建一个
Thread
,理想情况下将它传递给一个Runnable
.Thread
(您可以改为扩展并覆盖它的run
方法,但这通常是不受欢迎的。) - 你呼唤
start
它 - 调用的线程
start
继续执行其程序中的下一条语句 - 该
run
方法在单独的线程中执行,独立于启动它的线程。我认为这里的行为是“序列”的意思 - 由于以下情况之一,新线程最终会结束:
- 其
run
方法正常完成 - 它的
run
方法以异常完成 - 如果它是一个守护线程,它可以作为 JVM 终止的一部分而终止,因为所有非守护线程都退出了
- 其
In Java program, you create threads but they are not executed by Java alone. Java takes the help of the underlying OS to execute them. To allocate microprocessor time and to supervise all the threads' execution, the OS comes with Thread Scheduler. The entire responsibility of maintaining the sequence of execution of threads, where which thread should be given first preference than the other, lies with the thread scheduler. The scheduling depends on the algorithm of the scheduler. Many types of algorithms exist like preemptive and time slicing with round robin etc. It is a very complex algorithm that executes many times in a given time.
The scheduler maintains a pool of threads. When Java thread is started calling start()
method, it joins the pool of waiting threads.
State of Thread
1. New state: After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.
2. Runnable (Ready-to-run) state : A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start()
method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.
3. Running state : A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.
4. Dead state : A thread can be considered dead when its run()
method completes. If any thread comes on this state that means it cannot ever run again.
5. Blocked : - A thread can enter in this state because of waiting the resources that are hold by another thread