Thread
* is a sequential flow of the coontrool in the prgram
* is a light weight process..
* thread share memory space,
thread life cycle
***************
*new thread -object creation
*run - start()
*not runnable - sleep(), wait
* dead
* java.lang package is used to handle thread in java
class Ex1
{
public static void main(String arg[])
{
Thread obj=Thread.currentThread();
System.out.println(obj.getName());
System.out.println(obj.getPriority()); //0 to 9
System.out.println(obj.isAlive());
obj.setName("Jithesh");
obj.setPriority(9);
System.out.println(obj);
}
}
ex:2
class Ex2
{
public static void main(String arg[])
{
for(int i=0;i<10;i++)
{
System.out.println(i);
}
}
}
ex:3
class Ex2
{
public static void main(String arg[])
{
Thread obj=Thread.currentThread();
for(int i=0;i<10;i++)
{
try
{
obj.sleep(1000); // int msec
}catch(IntteruptedException e){}
System.out.println(i);
}
}
}
OR
class Ex2
{
public static void main(String arg[])throws Exception
{
Thread obj=Thread.currentThread();
for(int i=0;i<10;i++)
{
obj.sleep(1000); // int msec
System.out.println(i);
}
}
}
output
0
1
2
3
4
5
6
7
8
9
multithreading
*************
* extends Thread class
* implements Runnable Interface
class A extends Thread
{
A()
{
start(); // call run
}
public void run()
{
for(int i=0;i<10;i++)
{
try
{
sleep(1000); // int msec
}catch(IntteruptedException e){}
System.out.println(" A class "+i);
}
}
}
class B extends Thread
{
B()
{
start();
}
public void run()
{
for(int i=0;i<10;i++)
{
try
{
sleep(1000); // int msec
}catch(IntteruptedException e){}
System.out.println(" B class "+i);
}
}
}
class ex4
{
public static void main(String arg[])
{
A obj=new A();
B obj=new B();
}
}
output
A class 0
B class 0
....
...
ex: (implements Runnable Interface)
class A implements Runnable
{
Thread t;
A()
{
t=new Thread (this);
t.start();
}
public void run()
{
for(int i=0;i<10;i++)
{
try
{
t.sleep(1000); // int msec
}catch(IntteruptedException e){}
System.out.println(" A class "+i);
}
}
}
class B implements Runnable
{
Thread t;
B()
{
t=new Thread(this);
t.start();
}
public void run()
{
for(int i=0;i<10;i++)
{
try
{
t.sleep(1000); // int msec
}catch(IntteruptedException e){}
System.out.println(" B class "+i);
}
}
}
class ex5
{
public static void main(String arg[])
{
A obj=new A();
B obj=new B();
}
}
ex 6
class A extends Thread
{
A(String str)
{
super(str);
//setName(str);
start();
}
public void run()
{
for(int i=0;i<10;i++)
{
try
{
sleep(1000); // int msec
}catch(IntteruptedException e){}
System.out.println(getName()+i);
}
}
}
class ex5
{
public static void main(String arg[])
{
A obj=new A("Ilayaraja");
A obj1=new A("Vasudevan");
}
}