Creating thread program using runnable interface in java


Creating thread using Runnable interface

                Creating threads using runnable interface will not block you from using inheritance, Create a class that impliments Runnable interface and override a run method in it.

Program

 public class Sam implements Runnable {

	public void print() {
		for (int i = 1; i <= 10; i++) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("from Sam : " + i);
		}
	}

	public void run() {
		print();
	}
}

Since Runnable interface doesn?t have start method we cannot access it using the sam class object, so we have to create a new Thread object to imitate it. Check this below program to start a thread

public class Main {

	public static void main(String[] args) {
		Sam s1 = new Sam();

		Thread t1 = new Thread(s1);
		t1.start();

		for (int i = 11; i <= 20; i++) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("from Main : " + i);

		}
	}

}

Now run the program and check the output.



Related Post

Comments


©candidjava.com