logo

У Јави, нит увек постоји у било ком од следећих стања. Ове државе су:

  1. Нова
  2. Ацтиве
  3. Блокирано / Чека
  4. Укинуто

Објашњење различитих стања нити

Нова: Кад год се креира нова нит, она је увек у новом стању. За нит у новом стању, код још увек није покренут и стога није почео да се извршава.

Активан: .

    Нит, која је спремна за покретање, се затим премешта у стање за покретање. У стању покретања, нит може бити покренута или може бити спремна за покретање у било ком тренутку. It is the duty of the thread scheduler to provide the thread time to run, i.e., moving the thread the running state.
    Програм који имплементира вишенитност добија фиксни део времена за сваку појединачну нит. Свака нит ради кратак временски период и када се тај додељени временски одломак заврши, нит добровољно предаје ЦПУ другој нити, тако да и друге нити могу да раде током свог одсека времена. Кад год се деси такав сценарио, све те нити које су спремне да се покрену, чекајући свој ред за покретање, леже у стању за покретање. У стању које се може покренути, постоји ред у коме леже нити.Трчање:Када нит добије ЦПУ, она се помера из изводљивог у стање покретања. Уопштено говорећи, најчешћа промена стања нити је од покретања до покретања и поново до покретања.

На пример, нит (рецимо да јој је име А) можда жели да одштампа неке податке са штампача. However, at the same time, the other thread (let's say its name is B) is using the printer to print some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable to perform any execution and thus never consume any cycle of the Central Processing Unit (CPU). Hence, we can say that thread A remains idle until the thread scheduler reactivates thread A, which is in the waiting or blocked state.

Када главна нит тада позове методу јоин(), каже се да је главна нит у стању чекања. The main thread then waits for the child threads to complete their tasks. When the child threads complete their job, a notification is sent to the main thread, which again moves the thread from waiting to the active state.

Ако има много нити у стању чекања или блокирања, онда је дужност планера нити да одреди коју нит да изабере, а коју да одбије, а изабраној нити се тада даје могућност да се покрене.

Временско чекање: Понекад чекање доводи до гладовања. На пример, нит (име јој је А) је ушла у критични део кода и не жели да напусти тај критични део. У таквом сценарију, друга нит (име јој је Б) мора да чека заувек, што доводи до гладовања. To avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in the waiting state for a specific span of time, and not forever. A real example of timed waiting is when we invoke the sleep() method on a specific thread. The sleep() method puts the thread in the timed wait state. After the time runs out, the thread wakes up and start its execution from when it has left earlier.

Прекинуто: Нит достиже стање завршетка из следећих разлога:

  • Када нит заврши свој посао, она постоји или се нормално завршава.
  • Абнормални прекид:

Следећи дијаграм приказује различита стања укључена у животни циклус нити.

Животни циклус Јава нити

Тхреад.гетСтате() методом. Тхе јава.ланг.Тхреад.Стате

ц++ подељени стринг
 public static final Thread.State NEW 

 public static final Thread.State RUNNABLE 

 public static final Thread.State BLOCKED 

 public static final Thread.State WAITING 

 public static final Thread.State TIMED_WAITING 

  • спавати
  • придружи се са временским ограничењем
  • сачекајте са временским ограничењем
  • паркУнтил
 public static final Thread.State TERMINATED 

Следећи Јава програм приказује нека од стања горе дефинисане нити.

Назив документа: ТхреадСтате.јава

 // ABC class implements the interface Runnable class ABC implements Runnable { public void run() { // try-catch block try { // moving thread t2 to the state timed waiting Thread.sleep(100); } catch (InterruptedException ie) { ie.printStackTrace(); } System.out.println('The state of thread t1 while it invoked the method join() on thread t2 -'+ ThreadState.t1.getState()); // try-catch block try { Thread.sleep(200); } catch (InterruptedException ie) { ie.printStackTrace(); } } } // ThreadState class implements the interface Runnable public class ThreadState implements Runnable { public static Thread t1; public static ThreadState obj; // main method public static void main(String argvs[]) { // creating an object of the class ThreadState obj = new ThreadState(); t1 = new Thread(obj); // thread t1 is spawned // The thread t1 is currently in the NEW state. System.out.println('The state of thread t1 after spawning it - ' + t1.getState()); // invoking the start() method on // the thread t1 t1.start(); // thread t1 is moved to the Runnable state System.out.println('The state of thread t1 after invoking the method start() on it - ' + t1.getState()); } public void run() { ABC myObj = new ABC(); Thread t2 = new Thread(myObj); // thread t2 is created and is currently in the NEW state. System.out.println('The state of thread t2 after spawning it - '+ t2.getState()); t2.start(); // thread t2 is moved to the runnable state System.out.println('the state of thread t2 after calling the method start() on it - ' + t2.getState()); // try-catch block for the smooth flow of the program try { // moving the thread t1 to the state timed waiting Thread.sleep(200); } catch (InterruptedException ie) { ie.printStackTrace(); } System.out.println('The state of thread t2 after invoking the method sleep() on it - '+ t2.getState() ); // try-catch block for the smooth flow of the program try { // waiting for thread t2 to complete its execution t2.join(); } catch (InterruptedException ie) { ie.printStackTrace(); } System.out.println('The state of thread t2 when it has completed it's execution - ' + t2.getState()); } } 

Излаз:

 The state of thread t1 after spawning it - NEW The state of thread t1 after invoking the method start() on it - RUNNABLE The state of thread t2 after spawning it - NEW the state of thread t2 after calling the method start() on it - RUNNABLE The state of thread t1 while it invoked the method join() on thread t2 -TIMED_WAITING The state of thread t2 after invoking the method sleep() on it - TIMED_WAITING The state of thread t2 when it has completed it's execution - TERMINATED 

Објашњење: Кад год покренемо нову нит, та нит достиже ново стање. Када се метода старт() позове на нити, планер нити помера ту нит у стање које се може покренути. Кад год се метода јоин() позове на било којој инстанци нити, тренутна нит која извршава ту наредбу мора да сачека да ова нит заврши своје извршење, тј. да премести ту нит у прекинуто стање. Стога, пре него што се коначна изјава за штампање одштампа на конзоли, програм позива метод јоин() на нити т2, чинећи нит т1 чекајући док нит т2 заврши своје извршавање и тако нит т2 дође у прекинуто или мртво стање . Нит т1 иде у стање чекања јер чека да нит т2 заврши своје извршавање пошто је позвала метод јоин() на нити т2.