JAVA LAB 9
MULTITHREADING
Vibhuti purohit
22MIM10029
CODE:
public class Taskthreaddemo
{
public static void main(String[] args) {
Runnable printA = new
PrintChar('R',10); Runnable printB = new
PrintChar('Z',10); Runnable print100 =
new PrintNum(10);
Thread thread1 = new Thread(printA);
Thread thread2 = new Thread(printB);
Thread thread3 = new Thread(print100);
try {
thread1.start();
thread2.start();
thread3.start();
} catch (Exception e)
{ System.out.println("Thread " + "interrupted.
");
}
}
}
class PrintChar implements
Runnable{ private char chartoprint;
private int times;
public PrintChar(char c, int t)
{ chartoprint = c;
times = t;
public void run(){
for (int i=0; i< times; i++){
System.out.println(chartoprint);
}
}
class PrintNum implements
Runnable{ private int lastNum;
public PrintNum(int n){
lastNum=n;
}
public void run(){
for (int i=1; i<= lastNum; i++)
{ System.out.println(" "+ i);
}
}
}
As we all know multithreading has a beauty of providing
different outputs every time it is been executed therefore here, we
display 3 different outputs of the above given code.
OUPUT 1:
OUTPUT 2:
OUTPUT 3:
Here in this program we can change value of R, Z and the numbers
we want to be printed , also can alter the amount of time it should
take for another process to start by implementing it in milliseconds :
public class Taskthreaddemo
{
public static void main(String[] args) {
Runnable printA = new
PrintChar('R',100); Runnable printB = new
PrintChar('Z',100); Runnable print100 =
new PrintNum(10);
Thread thread1 = new Thread(printA);
Thread thread2 = new Thread(printB);
Thread thread3 = new Thread(print100);
try {
thread1.start();
thread1.sleep(1000);
thread2.start();
thread3.start();
} catch (Exception e)
{ System.out.println("Thread " + "interrupted.
");
}
}
class PrintChar implements
Runnable{ private char chartoprint;
private int times;
public PrintChar(char c, int t)
{ chartoprint = c;
times = t;
public void run(){
for (int i=0; i< times; i++){
System.out.println(chartoprint);
}
}
class PrintNum implements
Runnable{ private int lastNum;
public PrintNum(int n){
lastNum=n;
}
public void run(){
for (int i=1; i<= lastNum; i++)
{ System.out.println(" "+ i);
}
}
}