EEI4362_LAB3_PS_2023_2024
EEI4362_LAB3_PS_2023_2024
Discuss the use of threads, existing java thread methods and thread life cycle in Java.
Run the programs given inside boxes.
Java Thread Example 1 - extending Thread class.
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
Java Thread Example 2- implementing Runnable interface.
Briefly discuss the need for creating Thread class object explicitly
Page 1 of 7
Java Thread example 3 - sleep method in java
t1.start();
t2.start();
}
}
Discuss what happens if we keep a thread sleep for the specified time
Java Thread example 4 - trying to start a thread twice
Page 2 of 7
Exercise 01
Compare the two programs given as A and B
Program A
Program B
t1.run();
t2.run();
}
}
Exercise 2
Compare the two programs given as C and D
Page 3 of 7
Program C
t2.start();
t3.start();
}
}
Program D
class TestJoinMethod2 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod2 t1=new TestJoinMethod2();
TestJoinMethod2 t2=new TestJoinMethod2();
TestJoinMethod2 t3=new TestJoinMethod2();
t1.start();
try{
t1.join(1500);
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
Page 4 of 7
Java Thread example 5- Thread Pool
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class WorkerThread implements Runnable {
private String message;
public WorkerThread(String s){
this.message=s;
}
public void run() {
System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
Processmessage
System.out.println(Thread.currentThread().getName()+" (End)");
}
private void processmessage() {
try { Thread.sleep(2000); }
catch (InterruptedException e) {
e.printStackTrace(); }
}
}
Exercise 3
Compare the two programs given as E and F, with and without synchronized
methods.
Page 5 of 7
Program E
class Table{
void printTable(int n){
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
} } }
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
} }
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
} }
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Page 6 of 7
Program F
class Table{
synchronized void printTable(int n){
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
Page 7 of 7