Skip to content

Commit 8a22556

Browse files
committed
SynchroThread__同步线程
1 parent a79af9f commit 8a22556

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.cpucode.java.synchro;
2+
3+
/**
4+
* @author : cpucode
5+
* @date : 2021/2/9
6+
* @time : 12:17
7+
* @github : https://github.com/CPU-Code
8+
* @csdn : https://blog.csdn.net/qq_44226094
9+
*/
10+
public class SynchroThread{
11+
public static void main(String[] args) throws Exception{
12+
Thread add = new AddThreadTest();
13+
Thread dec = new DecThreadTest();
14+
15+
add.start();
16+
dec.start();
17+
18+
add.join();
19+
dec.join();
20+
21+
System.out.println(CounterTest.count);
22+
}
23+
}
24+
25+
class CounterTest{
26+
/**
27+
* 锁
28+
* */
29+
public static final Object lock = new Object();
30+
public static int count = 0;
31+
}
32+
33+
class AddThreadTest extends Thread{
34+
@Override
35+
public void run(){
36+
//对一个对象进行加锁
37+
synchronized (CounterTest.lock){
38+
//临界区
39+
CounterTest.count += 1;
40+
}
41+
}
42+
}
43+
44+
class DecThreadTest extends Thread{
45+
@Override
46+
public void run(){
47+
//对一个对象进行加锁
48+
synchronized (CounterTest.lock){
49+
//临界区
50+
CounterTest.count -= 1;
51+
}
52+
}
53+
}

0 commit comments

Comments
 (0)