java 同步 互斥_如何用JAVA实现同步互斥算法详解

展开全部

通过共享两个变量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. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值