当前位置 : 主页 > 编程语言 > c++ >

写2个线程,其中一个线程打印1~52,另一个线程打印A~z,打印顺序应该是12A34B45C……

来源:互联网 收集:自由互联 发布时间:2021-06-23
1 package Demo; 2 3 import java.util.concurrent.locks.Condition; 4 import java.util.concurrent.locks.Lock; 5 import java.util.concurrent.locks.ReentrantLock; 6 7 public class TestDemo { 8 public static void main(String[] args) { 9 Test t= n
 1 package Demo;
 2 
 3 import java.util.concurrent.locks.Condition;
 4 import java.util.concurrent.locks.Lock;
 5 import java.util.concurrent.locks.ReentrantLock;
 6 
 7 public class TestDemo {
 8     public static void main(String[] args) {
 9         Test t=new Test();
10         Count c=new Count(t);
11         Print p=new Print(t);
12         Thread t1=new Thread(c);
13         Thread t2=new Thread(p);
14         t1.start();
15         t2.start();
16 
17     }
18 }
19 
20 class Test{
21     private Lock lock=new ReentrantLock();
22     private Condition count_con=lock.newCondition();
23     private Condition print_con=lock.newCondition();
24     private int count=0;
25     private int sum=1;
26     private int i=0;
27     public void count(){
28         lock.lock();
29         try {
30             while(count==2){
31                 try {
32                     count_con.await();
33                 } catch (InterruptedException e) {
34                     e.printStackTrace();
35                 }
36             }
37             for (int i=1;i<=2;i++){
38                 System.out.print(sum++);
39                 count++;
40             }
41             i=0;
42             print_con.signal();
43         }finally {
44             lock.unlock();
45         }
46     }
47     private int cha=65;
48 
49     public void print(){
50         lock.lock();
51         while (i==1){
52             try {
53                 print_con.await();
54             } catch (InterruptedException e) {
55                 e.printStackTrace();
56             }
57         }
58         try {
59             System.out.print((char)(cha++));
60             i++;
61             count=0;
62             count_con.signal();
63         }finally{
64           lock.unlock();
65         }
66     }
67 }
68 
69 class Count implements Runnable{
70     private Test t;
71     public Count(Test t) {
72         this.t=t;
73     }
74     @Override
75     public void run() {
76         for (int i=0;i<26;i++) {
77             t.count();
78         }
79     }
80 }
81 class Print implements Runnable{
82     private Test t;
83 
84     public Print(Test t) {
85         this.t = t;
86     }
87     @Override
88     public void run() {
89         for (int i=0;i<26;i++) {
90             t.print();
91         }
92     }
93 }

疯狂Java讲义多线程课后练习。

网友评论