Creating a thread and running it

Creating a thread and running it

The following step should be used for creating thread:
Create a class that extends thread class or implements runnable interface. Both the thread class and runnable interface are found in java.lang package.

class myclass extends Thread
or class myclass implements Runnable

Now write a run() method as:

public void run()
{
//statements;
}

By default, this run() method is recognized and excuted by a threads.
Create an object to myclass

myclass obj = new myclass();

Now create a thread and attach the thread to the object obj

Thread t = new Thread(obj);

Run the thread. For this purpose, we should use start() method of thread class.

t.start();

Now thread start execution on the object of myclass.

Example
class mythread extends Thread
{
public void run()
{
for(int i=1;i<=10000;i++)
{
System.out.println(i);
}
}
}
class test
{
public static void main(String args[])
{
mythread obj = new mythread();
Thread t = new Thread(obj);
t.start();
}
}

Output:
1
2
3
4
5
.
.
.

Thread synchronization in java

When a thread is already acting on an object preventing any other thread from acting on the same object is called Thread synchronized or Thread safe. The object on which the threads are synchronized is called synchronized object. Thread synchronization is recommended when multiple threads are used on the same object.

Thread Scheduler in java

Thread scheduler decides which thread should run. There is no guarantee that which runnable thread will be chosen to run by the thread scheduler. Only one thread at a time can run in a single process.

Leave a Reply

Your email address will not be published. Required fields are marked *