Java Tutorial #10 Using threads with exceptions
Previous tutorial https://steemit.com/programming/@nicetea/java-tutorial-9-creating-a-carwash-app-with-queues
This is another tutorial about threads and the possible use-cases from them. Here you can find the last tutorial, with a multithreaded dice roll app:
https://steemit.com/programming/@nicetea/java-tutorial-8-creating-a-multithreaded-dice-roll-app
First, we will create 2 Thread classes which extend the Thread class.
Threadclass.java
public class ThreadClass extends Thread{
private int i;
public void run(){
for(i = 0;i<=20;i++){
System.out.println("Thread 1 "+ i);
try{
Thread.sleep(400);
} catch(Exception e){
}
}
}
}
ThreadClass2.java
public class ThreadClass2 extends Thread{
private int i;
public void run(){
for(i = 20;i>=0;i--){
if (i == 3)
break;
System.out.println("Thread 2 "+ i);
}
}
}
So basically the ThreadClass
is incrementing it's output every new iteration and sleeps for 400ms after every output.
The ThreadClass2
is decreasing it's output every new iteration starting from 20 to 0. When the number 3 is reached, it will break out of the current thread.
Main.java
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
ThreadClass t1 = new ThreadClass();
ThreadClass2 t2 = new ThreadClass2();
t1.run();
t2.run();
}
}
Two objects of the previously created classes are created with:
ThreadClass t1 = new ThreadClass();
ThreadClass2 t2 = new ThreadClass2();
t1.run();
t2.run();
And the output is:
Notice that the first thread output, will get printed out slower than the 2nd output! So just try it out by yourself.
Stay tuned!