Anonymous user
Mutex: Difference between revisions
→{{header|Java}}: - talke about Java's synchronized keyboard
m (Fixed lang tags.) |
(→{{header|Java}}: - talke about Java's synchronized keyboard) |
||
Line 196:
}
}</lang>
Java also has the synchronized keyword, which allows almost any object to be used to enforce mutual exclusion.
<lang java>public class Main {
static Object mutex = new Object();
static int i = 0;
public void addAndPrint()
{
System.out.print("" + i + " + 1 = ");
i++;
System.out.println("" + i);
}
public void subAndPrint()
{
System.out.print("" + i + " - 1 = ");
i--;
System.out.println("" + i);
}
public static void main(String[] args){
final Main m = new Main();
new Thread() {
public void run()
{
while (true) { synchronized(m.mutex) { m.addAndPrint(); } }
}
}.start();
new Thread() {
public void run()
{
while (true) { synchronized(m.mutex) { m.subAndPrint(); } }
}
}.start();
}
}</lang>
The "synchronized" keyword actually is a form of [[monitor]], which was a later-proposed solution to the same problems that mutexes and semaphores were designed to solve. More about synchronization may be found on Sun's website - http://java.sun.com/docs/books/tutorial/essential/concurrency/sync.html , and more about monitors may be found in any decent operating systems textbook.
=={{header|Objective-C}}==
|