Skip to content

Instantly share code, notes, and snippets.

@kohbo
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kohbo/cc8520759b97824e1175 to your computer and use it in GitHub Desktop.
Save kohbo/cc8520759b97824e1175 to your computer and use it in GitHub Desktop.
Multi-Threading
public class Hydrogen implements Runnable{
ReactionArea buff;
public Hydrogen(ReactionArea buff){
this.buff = buff;
}
public void run(){
for(int i = 0; i < 20; i++){
try{
buff.increWHydrogen(i);
Thread.sleep(100);
} catch(InterruptedException e){
e.printStackTrace();
System.exit(1);
}
}
}
}
public class Oxygen implements Runnable{
ReactionArea buff;
public Oxygen(ReactionArea buff){
this.buff = buff;
}
public void run(){
for(int i = 0; i < 20; i++){
try{
buff.increWOxygen(i);
Thread.sleep(100);
} catch(InterruptedException e){
e.printStackTrace();
System.exit(1);
}
}
}
}
public class ReactionArea {
public int waitingHydrogen = 0;
public int waitingOxygen = 0;
public synchronized void increWHydrogen(int index){
while(waitingHydrogen > 5){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
waitingHydrogen += 20;
System.out.println("The "+index+"th Hydrogen atom was added.");
notifyAll();
}
public synchronized void increWOxygen(int index){
while(waitingOxygen > 2){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
waitingOxygen += 10;
System.out.println("The "+index+"th Oxygen atom was added.");
notifyAll();
}
public synchronized void react(int index){
while(waitingHydrogen < 20 || waitingOxygen < 10){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
waitingHydrogen -= 20;
waitingOxygen -= 10;
System.out.println("The "+index+"th water molecule was added.");
notifyAll();
}
}
public class Reactor implements Runnable{
ReactionArea buff;
Reactor(ReactionArea buff){
this.buff = buff;
}
@Override
public void run() {
for(int i = 0; i < 20; i++){
try{
buff.react(i);
Thread.sleep(2000);
} catch(InterruptedException e){
e.printStackTrace();
System.exit(1);
}
}
}
}
public class Test {
public static void main(String[] args) {
ReactionArea reactarea = new ReactionArea();
Thread hydrogen = new Thread(new Hydrogen(reactarea));
Thread oxygen = new Thread(new Oxygen(reactarea));
Thread reactor = new Thread(new Reactor(reactarea));
hydrogen.run();
oxygen.run();
reactor.run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment