Multithreading in java
There are two ways to creating a thread
By creating a class that extends Thread (need to create function Run())
By creating a class that implements Runnable (we pass an object of this class as
a parameter to Thread constructor)
So in the end we need a Thread object to create a Thread.
class TaskThread extends Thread {
private int n;
public TaskThread(int n) {
this.n = n;
}
@Override
public void run() { //this need to be defined
System.out.println("Inside Thread's Run() with value " + n);
for (int i = n; i < n + 100; i++) {
System.out.print(i + " ");
}
System.out.println("\nExiting Thread's Run() that has value " + n);
}
}
class TaskRunnable implements Runnable {
private int n;
public TaskRunnable(int n) {
this.n = n;
}
@Override
public void run() { //this need to be defined
System.out.println("Inside Runnable's Run() with value " + n);
for (int i = n; i < n + 100; i++) {
System.out.print(i + " ");
}
System.out.println("\nExiting Runnable's Run() that has value " + n);
}
}
public class Main {
public static void main(String[] args) {
TaskThread t1 = new TaskThread(0);
Thread t2 = new Thread(new TaskRunnable(100));
t1.start();
t2.start();
}
}
//we can set priority[1,10] to a thread. 5 is by default
//t1.setPriority(7)
//we can wait till a thread dies using t1.join().
//control will go to next line only when t1 has completed it’s execution
class TaskThread extends Thread {
private String ch;
public TaskThread(String ch) {
this.ch = ch;
}
@Override
public void run() { //this need to be defined
System.out.println("\nInside Thread's Run() with value " + ch);
for (int i = 0; i < 100; i++) {
System.out.print(ch + " ");
}
System.out.println("\nExiting Thread's Run() that has value " + ch);
}
}
class TaskRunnable implements Runnable {
private String ch;
public TaskRunnable(String ch) {
this.ch = ch;
}
@Override
public void run() { //this need to be defined
System.out.println("\nInside Runnable's Run() with value " + ch);
for (int i = 0; i < 100; i++) {
System.out.print(ch + " ");
}
System.out.println("\nExiting Runnable's Run() that has value " + ch);
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
TaskThread t1 = new TaskThread("🔴");
Thread t2 = new Thread(new TaskRunnable("🟡"));
t2.setPriority(10);
TaskThread t3 = new TaskThread("🟢");
Thread t4 = new Thread(new TaskRunnable("🔵"));
t1.start();
t2.start();
//run following lines only when t2 has died
t2.join();
t3.start();
t4.start();
}
}
//Thread.sleep(1000) to sleep for 1 second
//Thread.yield() causes the currently executing thread object to temporarily pause and
allow other threads to execute.