Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
10
Task/Mutex/Java/mutex-1.java
Normal file
10
Task/Mutex/Java/mutex-1.java
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import java.util.concurrent.Semaphore;
|
||||
|
||||
public class VolatileClass{
|
||||
public Semaphore mutex = new Semaphore(1); //also a "fair" boolean may be passed which,
|
||||
//when true, queues requests for the lock
|
||||
public void needsToBeSynched(){
|
||||
//...
|
||||
}
|
||||
//delegate methods could be added for acquiring and releasing the mutex
|
||||
}
|
||||
10
Task/Mutex/Java/mutex-2.java
Normal file
10
Task/Mutex/Java/mutex-2.java
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
public class TestVolitileClass throws Exception{
|
||||
public static void main(String[] args){
|
||||
VolatileClass vc = new VolatileClass();
|
||||
vc.mutex.acquire(); //will wait automatically if another class has the mutex
|
||||
//can be interrupted similarly to a Thread
|
||||
//use acquireUninterruptibly() to avoid that
|
||||
vc.needsToBeSynched();
|
||||
vc.mutex.release();
|
||||
}
|
||||
}
|
||||
35
Task/Mutex/Java/mutex-3.java
Normal file
35
Task/Mutex/Java/mutex-3.java
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
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();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue