본문 바로가기
Java, JavaScript

Thread wait notify simple example in Java

by swconsulting swconsulting 2017. 12. 24.


1) Start and Wait Java Code

package common;


public class CommonMain {


public void Run() {


Thread workerThread = new Thread(new WorkerThread());


synchronized(workerThread) {

try {

System.out.println("Thread start()");

workerThread.start();


System.out.println("Thread wait()");

workerThread.wait();


System.out.println("Thread wait() finish~!");


} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}



2) Running Thread Java Code

package common;


public class WorkerThread implements Runnable  {


@Override

public void run() {


synchronized(this) {

try {

for(int i = 0; i < 10; i++) {

Thread.sleep(500);


System.out.println("WorkerThread i = " + i);

}


notify();


} catch (InterruptedException e) {

e.printStackTrace();

}

}


}


}



3) Output Result

Thread start()

Thread wait()

WorkerThread i = 0

WorkerThread i = 1

WorkerThread i = 2

WorkerThread i = 3

WorkerThread i = 4

WorkerThread i = 5

WorkerThread i = 6

WorkerThread i = 7

WorkerThread i = 8

WorkerThread i = 9

Thread wait() finish~!



댓글0