Multithreading

 Practical implementation of thread.

Example 1:

//example of thread

class Hy{

public static void show(){

for (int i=0;i<5 ;i++ ) 

{

System.out.println("HY");

try{Thread.sleep(500);} catch(Exception e){}

}

}

}

/*

here we are usig thread.sleep its main

*function is to suspend the thread 

*/

class Hello{

public static void show(){

for(int j=0;j<5;j++)

{

System.out.println("Hello");

try{Thread.sleep(500);} catch(Exception e){}

}

}

}

class ThreadDemo{

public static void main(String[] args) {

Hy obj1 = new Hy();

Hello obj2= new Hello();

obj1.show();

obj2.show();

}

}

OUTPUT:

HY

HY

HY

HY

HY

Hello

Hello

Hello

Hello

Hello

Example2:
//example of thread2
class Hy extends Thread{
public  void run(){
for (int i=0;i<5 ;i++ ) 
{
System.out.println("HY");
try{Thread.sleep(500);} catch(Exception e){}
}
}
}

class Hello extends Thread{
public void run(){
for(int j=0;j<5;j++)
{
System.out.println("Hello");
try{Thread.sleep(500);} catch(Exception e){}

}
}
}
class ThreadDemo{
public static void main(String[] args) {
Hy obj1 = new Hy();
Hello obj2= new Hello();
obj1.start();
try{Thread.sleep(10);}catch(Exception e){}
obj2.start();
}
}
 OUTPUT:
HY
Hello
HY
Hello
HY
Hello
HY
Hello
HY
Hello

EXAMPLE 3:
class ThreadDemo2
{
public static void main(String[] args) {
Thread t = Thread.currentThread();
System.out.println("current thread"+t);
t.setName("MY THREAD");
System.out.println("After name change:"+t);
              try{
for (int i=5;i>0 ;i-- ) {
System.out.println(i);
Thread.sleep(1000);
}
}
catch(Exception e){}

}
}
OUTPUT:
current threadThread[main,5,main]
After name chaneg:Thread[MY THREAD,5,main]
5
4
3
2
1

EXAMPLE 3:
class Hy implements Runnable{
public void run(){
for (int i=0;i<5 ;i++ ) {
System.out.println("Hy");
try{Thread.sleep(500);}catch(Exception e){}
}
}
}
class Hello implements Runnable
{
public void run()
{
for (int i=0;i<5;i++) {
System.out.println("Hello");
try{Thread.sleep(500);}catch(Exception e){}
}
}
}
class ThreadDemo3
{
public static void main(String[] args) {

//creating objects for Hy class and Hello class
Runnable obj1= new Hy();
Runnable obj2 = new Hello();

//creating two threas and linking with the objects
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);

t1.start();
try{Thread.sleep(10);} catch(Exception e){}
t2.start();
}
}
OUTPUT:Hy
Hello
Hy
Hello
Hy
Hello
Hy
Hello
Hy
Hello





Comments

Popular posts from this blog

Java Program to find average of Three numbers

JAVA(String Buffer and String Builder

Java Swing Complete examples step by step(make a project with swing)