-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadNoSynchronized.java
More file actions
57 lines (46 loc) · 1.17 KB
/
Copy pathThreadNoSynchronized.java
File metadata and controls
57 lines (46 loc) · 1.17 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
/**
* 功能:理解线程同步与异步
* 此程序为线程异步
*
*/
public class ThreadNoSynchronized {
public static void main(String[] args) {
ShareData oshare = new ShareData();
ThreadDemo td1 = new ThreadDemo("Thread1", oshare);
ThreadDemo td2 = new ThreadDemo("Thread2", oshare);
td1.start();
td2.start();
}
}
class ShareData {
public static String szData = "";
}
class ThreadDemo extends Thread {
private ShareData oShare;
ThreadDemo() {}
ThreadDemo(String szName, ShareData oShare) {
super(szName);
this.oShare = oShare;
}
public void run() {
for(int i=0; i<5; i++) {
if(this.getName().equals("Thread1")) {
oShare.szData = "这是第1个线程";
try {
Thread.sleep((int)Math.random() * 100);
}
catch(InterruptedException e) {
System.out.println(this.getName() + ":" + oShare.szData);
}
System.out.println(this.getName() + ":" + oShare.szData);
else if(this.getName().equals("Thread2")) {
oShare.szData = "这是第2个线程";
}try {
Thread.sleep((int)Math.random() * 100);
} catch(InterruptedException e) {
}
System.out.println(this.getName() + ":" + oShare.szData);
}
}
}
}