展开全部
通过共享两个变量62616964757a686964616fe78988e69d8331333337613765 flag 和turn来实现同步。
1. package mutiple_thread;
2.
3. public class OS_SYN_A3{
4. public static int flag[]=new int [3];
5. public static int turn=0;
6. public static int cnt=0;
7. public static void main(String args[]){
8. class proo implements Runnable{
9. public proo(){
10.
11. }
12. @Override
13. public void run() {
14. // TODO Auto-generated method stub
15. while(true){
16. flag[1]=1;
17. turn=2;
18. while(flag[2]==1&&turn==2){
19.
20. }
21. if(cnt==5){
22. flag[1]=0;
23. }else{
24. cnt++;
25. System.out.println("pro ++! now id"+cnt);
26. flag[1]=0;
27. }
28. }
29. }
30.
31. }
32.
33. class conn implements Runnable{
34.
35. @Override
36. public void run() {
37. // TODO Auto-generated method stub
38. while(true){
39. flag[2]=1;
40. turn=1;
41. while(flag[1]==1&&turn==1){
42.
43. }
44. //临界区
45. if(cnt==0){
46. flag[2]=0;
47. }else{
48. cnt--;
49. System.out.println("con --! now id"+cnt);
50. //退出临界区
51. flag[2]=0;
52. }
53. }
54. }
55. }
56. new Thread(new proo()).start();
57. new Thread(new conn()).start();
58. }
59.
60. }