Multithreading in Java
Multithreading in Java
Thread Creation
Threads can be created by using two mechanisms:
1) Extending the Thread class
2) Implementing the Runnable Interface
By extending the Thread class
class MyThread extends Thread
{
public void run()
{
for (int i = 1; i <= 5; i++)
{
System.out.println(i + " from " + Thread.currentThread().getName());
try
{
Thread.sleep(1000); // Pause the thread for 1 second
}
catch (InterruptedException e)
{
System.out.println(e);
}
}
}
}
public class TestThread
{
public static void main(String[] args)
{
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
}
}
Output (Sample)
1 from Thread-0
1 from Thread-1
2 from Thread-0
2 from Thread-1
3 from Thread-0
3 from Thread-1
4 from Thread-0
4 from Thread-1
5 from Thread-0
5 from Thread-1
Syntax:
public interface Runnable
{
public void run();
}
// Class implementing the Runnable interface
class MyRunnable implements Runnable
{
public void run()
{
for (int i = 1; i <= 5; i++)
{
System.out.println(i + " from " + Thread.currentThread().getName());
try
{
Thread.sleep(1000); // Pause for 1 second
}
catch (InterruptedException e)
{
System.out.println(e);
}
}
}
}
// Create Thread objects, passing the Runnable objects to the Thread constructor
Thread t1 = new Thread(myRunnable1);
Thread t2 = new Thread(myRunnable2);
// Start the threads
t1.start();
t2.start();
}
}