Created
November 28, 2012 17:50
-
-
Save Frdnspnzr/4162852 to your computer and use it in GitHub Desktop.
Threadaufgabenkram
This file contains 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
/* | |
* Manchmal benutzen wir github, um Uni-Aufgaben zu tauschen. | |
* | |
* Das tut uns leid. | |
* | |
*/ | |
package blatt3; | |
public class MultiThreaded { | |
volatile int status; | |
private Dumper dumper; | |
public static void main(String[] args) { | |
System.out.print("BEGIN"); | |
new MultiThreaded().execute_input(); | |
System.out.print("END"); | |
} | |
public MultiThreaded() { | |
this.status = 0; | |
this.dumper = new Dumper(this); | |
this.dumper.start(); | |
} | |
public void execute_input() { | |
int input; | |
while (true) { | |
try { | |
input = System.in.read(); | |
} catch (Exception e) { | |
input = 0; | |
} | |
switch (input) { | |
case '1': | |
case '2': | |
case '3': | |
status = input - '0'; | |
break; | |
case 'q': | |
//Nach beenden des Programmes auch zweiten Thread terminieren | |
//Dieser würde sonst ununterbrochen weiterlaufen und die JVM | |
//würde nicht terminieren | |
//(Aufgabenteil c) | |
this.dumper.stopDumping(); | |
return; | |
default: | |
//Nichts | |
} | |
} | |
} | |
public int getStatus() { | |
return this.status; | |
} | |
} | |
public class Dumper extends Thread { | |
private MultiThreaded invokedBy; | |
//Aufgabenteil c | |
private boolean doDump = true; | |
public Dumper(MultiThreaded invokedBy) { | |
this.invokedBy = invokedBy; | |
} | |
@Override | |
public void run() { | |
//Bis das Programm beendet wurde (Aufgabenteil c) | |
while (this.doDump) { | |
System.out.println(this.invokedBy.getStatus()); | |
try { | |
Thread.sleep(300); | |
} catch (InterruptedException e) { | |
//Aufwachen ignorieren (Das gibt potenziell den Status zu oft aus) | |
} | |
} | |
} | |
//Stop-Methode für Aufgabenteil c | |
public void stopDumping() { | |
this.doDump = false; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment