Created
May 21, 2018 22:56
-
-
Save peterjurkovic/7920b50cdce888379f2983bd0e9f8593 to your computer and use it in GitHub Desktop.
ProducerConsumer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This Java source file was generated by the Gradle 'init' task. | |
*/ | |
public class App { | |
public static void main(String[] args) { | |
Shared shared = new Shared(); | |
new Produser(shared).start(); | |
new Consumer(shared).start(); | |
} | |
static class Shared{ | |
private char c; | |
private boolean writable = true; | |
synchronized void setCharactoer(char c){ | |
while ( ! writable ) { | |
// System.out.println("Now is writable c: " + c); | |
try{ | |
wait(); | |
}catch (Exception e) { | |
System.err.println(e.getMessage()); | |
} | |
} | |
this.c = c; | |
writable = false; | |
// System.out.println("set notify()" ); | |
notifyAll(); | |
} | |
synchronized char readChar(){ | |
while (writable) { | |
try{ | |
wait(); | |
}catch (Exception e) { | |
System.err.println(e.getMessage()); | |
} | |
} | |
writable = true; | |
// System.out.println("get notify()" ); | |
notify(); | |
return c; | |
} | |
} | |
static class Produser extends Thread{ | |
private final Shared shared; | |
public Produser(Shared shared) { | |
this.shared = shared; | |
} | |
@Override | |
public void run() { | |
for(char ch = 'A'; ch <= 'Z'; ch++){ | |
synchronized (shared) { | |
shared.setCharactoer(ch); | |
System.out.println(ch + " produced by producer"); | |
} | |
} | |
} | |
} | |
static class Consumer extends Thread{ | |
private final Shared shared; | |
public Consumer(Shared shared) { | |
this.shared = shared; | |
} | |
@Override | |
public void run() { | |
char ch; | |
do { | |
synchronized (shared) { | |
ch = shared.readChar(); | |
System.out.println(ch + " consumed by consumer"); | |
} | |
} while (ch != 'Z'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment