Stop thread using own flag and interrupt method

Here is the sample code that explains how to stop thread using own flag and interrupt method respectively.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
public class Main {
 
    static interface IClosableThread {
        void start();
 
        void close();
    }
 
    static class StopThreadUsingFlag extends Thread implements IClosableThread {
        private boolean stopThis = false;
 
        public void run() {
            try {
                while (this.stopThis == false) {
                    System.out.print(".");
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
            }
 
            System.out.println();
            System.out.println("Finished!");
        }
 
        public void close() {
            this.stopThis = true;
 
            try {
                this.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
 
    static class StopThreadUsingInterrupt extends Thread implements
            IClosableThread {
        public void run() {
            try {
                while (!this.isInterrupted()) {
                    System.out.print(".");
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
            }
 
            System.out.println();
            System.out.println("Finished!");
        }
 
        public void close() {
            this.interrupt();
 
            try {
                this.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
 
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
 
        IClosableThread thread = new Main.StopThreadUsingFlag();
        thread.start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.close();
 
        thread = new Main.StopThreadUsingInterrupt();
        thread.start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.close();
 
    }
}