Sei sulla pagina 1di 4

• Problem 01: Thread : Create thread by extending Thread class with sleep() method

package threadexamp;

class ex1 extends Thread{


@Override
public void run()
{
for(int i=0;i<5;i++)
{
try{
Thread.sleep(500);
}catch(Exception e){

}
System.out.println(i);
}

public class ThreadExamp {

public static void main(String[] args) {


ex1 t1=new ex1();
ex1 t2=new ex1();
t1.start();
t2.start();

}
• Problem 02: Thread : Create thread by extending Thread class for comparing with problem 3

class test1 extends Thread{

@Override
public void run()
{
System.out.println("Run method executed by child Thread");

public static void main(String[] args) {


test1 t1=new test1();
t1.start();

System.out.println("Main method executed by main thread");


}
}

Problem 03: Thread : Create thread by implementing Runnable interface


class Test implements Runnable {
@Override
public void run()
{
System.out.println("Run method executed by child Thread");
}
public static void main(String[] args)
{

Test t = new Test();

Thread t1 = new Thread(t);

t1.start();
System.out.println("Main method executed by main thread");
}
}
Problem 04: Thread : Create thread by implementing Runnable interface for comparing with Problem 03
where run() executing following thread rule(main() method will be executed first then others). But in
Problem 04 run() executing in normal sequence also run() executing following thread rule when passing
object through thread.
class Test implements Runnable {
@Override
public void run()
{
System.out.println("Run method executed by child Thread");
}
public static void main(String[] args)
{

Test t = new Test();


t.run();
Thread t1 = new Thread(t);
t1.start();
System.out.println("Main method executed by main thread");
}
}

Problem 05: Thread : Create thread and use join() method

class Joinmethod 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[]){
Joinmethod t1=new Joinmethod();
Joinmethod t2=new Joinmethod();
Joinmethod t3=new Joinmethod();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}

t2.start();
t3.start();
}
}
Problem 06: Thread : Create thread and use join() method

class Joinmethod 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[]){
Joinmethod t1=new Joinmethod();
Joinmethod t2=new Joinmethod();
Joinmethod t3=new Joinmethod();
t1.start();
try{
t1.join(1500);
}catch(Exception e){System.out.println(e);}

t2.start();
t3.start();
}
}

Potrebbero piacerti anche