简体   繁体   English

使用Java线程进行互斥

[英]mutual exclusion using thread of java

I have this code , It is mutual exclusion algorithm 我有这个代码,这是互斥算法

turn = 0 // shared control variable    

while (turn != i);

// CS

turn = (turn + 1) % n;

I know how thread works but really I'm little weak in using thread in java so please any suggestion to help me to understand how to convert it in real code using thread of java 我知道线程如何工作,但实际上我在使用Java中的线程方面并不弱,因此请提出任何建议以帮助我了解如何使用Java线程在真实代码中进行转换

sorry for my bad english 对不起,我的英语不好

Mutual exclusion is typically achieved, in the simplest form, by marking a method as synchronized. 互斥通常以最简单的形式通过将方法标记为同步来实现。 By marking an object's method as synchronized, only one thread can ever execute that object's method at a time. 通过将对象的方法标记为已同步,一次只能有一个线程执行该对象的方法。 The object owning the method is the monitor. 拥有该方法的对象是监视器。

Additionally, you can define a synchronized block in the code itself, passing it the object to act as the monitor. 另外,您可以在代码本身中定义一个同步块,将对象传递给它以充当监视器。

I believe you could achieve the same thing in a simpler fashion, by defining a Runnable object which has the logic you want done. 我相信您可以通过定义具有您想要执行的逻辑的Runnable对象,以更简单的方式实现相同的目的。 Where you want the mutual exclusion, define a synchronized method. 在需要互斥的地方,定义一个同步方法。

Then that Runnable instance can be passed to as many Threads you need. 然后,可以将该Runnable实例传递给所需的多个线程。 As they all reference the same Runnable, calls into the synchronized method will be mutually exclusive. 由于它们都引用相同的Runnable,因此对同步方法的调用将是互斥的。

This is not the only way, but it should be what you're after. 这不是唯一的方法,但应该是您所追求的。 Hope this helps. 希望这可以帮助。

this code is not mutually exclusive, consider this execution- 此代码不是互斥的,请考虑以下执行-

  1. thread 0 enters the code and CS and then increments turn to 1 in the last line. 线程0输入代码和CS,然后在最后一行中递增到1。
  2. thread 1 enters the CS as turn equals 1,and stays 线程1等于1进入CS并停留
  3. now thread 0 goes back to the first line and sets turn to 0 and then enters the CS together with thread 1 现在线程0返回第一行,并将turn设置为0,然后与线程1一起进入CS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM