THREADS IN JAVA
Creating threads by constructor
class mythread implements Runnable //creates second thread
{
Thread t;
int i;
mythread()
{
t=new
Thread(this,"mythread"); //creates new second thread
t.start();
//start the thread
}
public void run()
{
for(i=0;i<5;i++)
{
System.out.println("child thread " + i);
}
}
}
public class Thread2 { public static void main(String[] args) { new mythread(); //create new second thread }}
EXAMPLE
class mythread implements Runnable
{
int i ;
public void run()
{
for(i=0;i<5;i++)
{
System.out.println("Child thread :" + i);
}
}
}
class createthread
{
public static
void main(String[ ] args)
{
mythread m1=new mythread();
Thread th=new Thread(m1,"mythread");
th.start();
}
}
sleep() :-
makes currently executing thread to sleep for milliseconds.
Syntax:-
void sleep(long
milliseconds);
class mythread
implements Runnable
{
Thread t; int i; mythread() { t=new
Thread(this,"mythread"); //creates new second thread t.start();
//start the thread
} }
public void run() { try {
for(i=0;i<5;i++) {
System.out.println("child thread " + “hello world”);
Thread.sleep(1000); } } catch(Exception
e) {
}
System.out.println("Exitng child thread"); }
}
public class Thread2 {
public static void
main(String[] args)
{
new
mythread(); //create new second thread
int i;
try
{
for(i=0;i<5;i++)
{
System.out.println("Main thread " + i);
Thread.sleep(3000);
}
}
catch(Exception
e)
{
}
System.out.println("Exitng Main thread");
}
}
isAlive() :-
Returns the value true or false depending on thread is
terminated or not.
getname():-
Returns the name of the thread specified.
currentThread() :-
When a program is started thread is created
automatically that is main thread and the main thread can be accessed using the
current thread method of the main class.
class mythread implements Runnable //creates second
thread{ Thread t; int i; mythread() { t=new
Thread(this,"mythread"); //creates new second thread
System.out.println(" Child
thread :
" + t.getName() );System.out.println("Is Thread Alive ? " +
t.isAlive());
t.start(); //start the threadSystem.out.println("Is Thread Alive ? " +
t.isAlive());
}
public void
run() {
for(i=0;i<5;i++) {
System.out.println("child thread " + i);
}
}
}
public class methods {
public static
void main(String[] args)
{
mythread m1= new mythread();
System.out.println("The main
thread is :" + Thread.currentThread().getName());
}
}
Thread priorities
Nice post..thank you for sharing this blog
ReplyDeletesalesforce training in Marathahalli
salesforce admin training in Marathahalli
salesforce developer training in Marathahalli
Awesome blog.. I got more information in this blog
ReplyDeletejava training in Bangalore
spring training in Bangalore
java training institute in Bangalore
spring and hibernate training in Bangalore