2018년 4월 3일 화요일

[Java] Waking a Thread from Sleep



1. Waking a Thread from Sleep


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
static void testThread() {
    Thread thread = new Thread() {
        @Override
        public void run() {
            for( int i=0; i < 5; i++ ) {
                try {
                    Thread.sleep(1000);
                    System.out.println("Thread: " + i);
                } catch (InterruptedException e) {
                    System.out.println("Thread: interrupted !");
                    break;
                }
            }
        }
    };
    thread.start();
    try {
        Thread.sleep(3000);
        thread.interrupt();
        thread.join();
    } catch (InterruptedException e) {
    }
    System.out.println("Thread: test end !");
}


Result:
Thread: 0
Thread: 1
Thread: 2
Thread: interrupted !
Thread: test end !



댓글 없음:

댓글 쓰기