-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStopThreadUnsafe.java
More file actions
85 lines (72 loc) · 1.97 KB
/
StopThreadUnsafe.java
File metadata and controls
85 lines (72 loc) · 1.97 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
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
85
package Thread;
/**
* @author [email protected]
* Created by zacky on 21:32.
*/
public class StopThreadUnsafe {
public static User u = new User();
public static class User {
private int id;
private String name;
public User() {
id = 0;
name = "0";
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
public static class ReadObjectThread extends Thread{
@Override
public void run(){
while (true){
synchronized (u){
if(u.getId() != Integer.parseInt(u.getName())){
System.out.println(u.toString());
}
}
Thread.yield();
}
}
}
private static class ChangeObjectThread extends Thread {
@Override
public void run() {
while (true) {
synchronized (u) {
int v = (int) (System.currentTimeMillis() / 1000);
u.setId(v);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
u.setName(String.valueOf(v));
}
Thread.yield();
}
}
}
public static void main(String[] args) throws InterruptedException{
new ReadObjectThread().start();
while (true){
Thread t = new ChangeObjectThread();
t.start();
Thread.sleep(150);
t.stop();
}
}
}