File tree Expand file tree Collapse file tree 4 files changed +72
-64
lines changed
codes/concurrent/src/main/java/io/github/dunwu/javase/concurrent/sync Expand file tree Collapse file tree 4 files changed +72
-64
lines changed Load Diff This file was deleted.
Load Diff This file was deleted.
Original file line number Diff line number Diff line change 1+ package io .github .dunwu .javase .concurrent .sync ;
2+
3+
4+ @ SuppressWarnings ("all" )
5+ public class SynchronizedDemo01 {
6+
7+ public static void main (String [] args ) {
8+ new Thread (new UnSynchronizedDemo .MyThread ("线程A" )).start ();
9+ new Thread (new UnSynchronizedDemo .MyThread ("线程B" )).start ();
10+ new Thread (new UnSynchronizedDemo .MyThread ("线程C" )).start ();
11+ }
12+
13+ static class MyThread implements Runnable {
14+
15+ private int ticket = 5 ; // 假设一共有5张票
16+
17+ @ Override
18+ public void run () {
19+ for (int i = 0 ; i < 100 ; i ++) {
20+ synchronized (this ) { // 要对当前对象进行同步
21+ if (ticket > 0 ) { // 还有票
22+ try {
23+ Thread .sleep (300 ); // 加入延迟
24+ } catch (InterruptedException e ) {
25+ e .printStackTrace ();
26+ }
27+ System .out .println ("卖票:ticket = " + ticket --);
28+ }
29+ }
30+ }
31+ }
32+ }
33+ };
Original file line number Diff line number Diff line change 1+ package io .github .dunwu .javase .concurrent .sync ;
2+
3+ /**
4+ * 未同步的多线程示例,因为存在竞态条件,所以线程不安全。
5+ * @author Zhang Peng
6+ * @date 2018/5/21
7+ */
8+ @ SuppressWarnings ("all" )
9+ public class UnSynchronizedDemo {
10+
11+ public static void main (String [] args ) {
12+ new Thread (new MyThread ("线程A" )).start ();
13+ new Thread (new MyThread ("线程B" )).start ();
14+ new Thread (new MyThread ("线程C" )).start ();
15+ }
16+
17+ static class MyThread extends Thread {
18+
19+ private int ticket = 5 ; // 假设一共有5张票
20+
21+ public MyThread (String name ) {
22+ super (name );
23+ }
24+
25+ @ Override
26+ public void run () {
27+ for (int i = 0 ; i < 100 ; i ++) {
28+ if (ticket > 0 ) { // 还有票
29+ try {
30+ Thread .sleep (300 ); // 加入延迟
31+ } catch (InterruptedException e ) {
32+ e .printStackTrace ();
33+ }
34+ System .out .println (Thread .currentThread ().getName () + " 卖票:ticket = " + ticket --);
35+ }
36+ }
37+ }
38+ }
39+ }
You can’t perform that action at this time.
0 commit comments