File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
thread/src/com/cpucode/java/synchro Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments