Created
November 26, 2017 21:38
-
-
Save derfalx/e6a4ae74e3e09c0051d58200ba0852bc to your computer and use it in GitHub Desktop.
Threading example
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
package tech.falx.mono.threading; | |
public class Main { | |
public static void main(String[] args) { | |
new Main(); | |
} | |
public Main() { | |
CounterThread thread = new CounterThread(); | |
thread.setName( "doStuff" ); | |
AnotherThread main = new AnotherThread(); | |
main.setName( "foobar" ); | |
main.start(); // CounterThread run in dem MainThread ausführen | |
thread.start(); // CounterThread in einem eigenen Thread starten | |
try | |
{ | |
thread.join(); // Warten auf thread "thread" | |
main.join(); // Wartren auf thread "main" | |
} | |
catch ( InterruptedException e ) | |
{ | |
e.printStackTrace(); | |
} | |
} | |
private void doStuff ( int i ){ | |
synchronized(this) // synchronized benötigt weil wait() und notify() | |
{ | |
try | |
{ | |
this.wait(); | |
System.out.println( Thread.currentThread().getName() + ": i = " + i ); // sobalds frei ist belegen wir es | |
System.out.flush(); | |
Thread.sleep( 100 ); | |
} | |
catch ( InterruptedException e ) | |
{ | |
e.printStackTrace(); | |
} | |
} | |
} | |
private void foobar (int i){ | |
synchronized ( this) | |
{ | |
try | |
{ | |
System.out.println( Thread.currentThread().getName() + ": i = " + i ); // sobalds frei ist belegen wir es | |
System.out.flush(); | |
this.notify(); // geben bescheid dass das object wieder frei ist | |
Thread.sleep( 300 ); | |
} | |
catch ( InterruptedException e ) | |
{ | |
e.printStackTrace(); | |
} | |
} | |
} | |
// TCPSendThread | |
class CounterThread extends Thread // Thread implementierungen erben von Thread | |
{ | |
@Override public void run () // Main Funktion des Threads | |
{ | |
for(int i = 0; i < 25; i++) { | |
Main.this.doStuff( i ); | |
} | |
} | |
} | |
class AnotherThread extends Thread | |
{ | |
@Override public void run() { | |
for(int i = 0; i < 25; i++) { | |
Main.this.foobar(i); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment