-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRunnableDemo.java
More file actions
57 lines (44 loc) · 1.18 KB
/
Copy pathRunnableDemo.java
File metadata and controls
57 lines (44 loc) · 1.18 KB
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
package com.multithread;
import com.util.PrintUtil;
/**
* Create a Thread by Implementing a Runnable.
*
* This idiom is more general, because the Runnable object can subclass other class.
* Runnable task often be seperated from Thread object.
*
* @author 212331901
*
*/
public class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
public static int count;
public String getThreadName() {
return threadName;
}
public void setThreadName(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
PrintUtil.print("Running: " + this.getThreadName());
for(int i = 4; i > 0; i--){
PrintUtil.print("Thread: " + this.getThreadName() + ", at " + i);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
PrintUtil.print("Thread: " + this.getThreadName() + " exiting.");
}
public void start() {
if(this.getThreadName() == null || this.getThreadName().length() == 0)
this.setThreadName("Thread-" + ++count );
PrintUtil.print("Starting " + this.getThreadName());
if(t == null) {
t = new Thread(this, this.getThreadName());
t.start();
}
}
}