Skip to content

Instantly share code, notes, and snippets.

@derfalx

derfalx/Main.java

Created Nov 26, 2017
Embed
What would you like to do?
Threading example
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