java multi-threading runnable demo

Multi threading is to spin up multiple threads to do stuff concurrently, each tread contains one running task. In java, there is an Runnalbe interface that requires the implemtation of run method. When you implement the Runnable interface, you then override the run mehtod to do your custom task, and the task will be started to run in a thread when triggered. Implementing the Runnable interface and extending the Thread class can both be used for multi-threading, but implementing the Runnable is more preferred than extending the Thread class. One of the reason being that you can implement multiple interfaces but you can only extend from one class. By using Runnable interface, it gives you more flexibility such that you can extend from another class but still be able to do the multi-treading by implementing the Runnable interface.

Here is a basic usage of using the Runnalbe interface for mutli-threading.

public class RunnableDemo{	
	public static class Counter implements Runnable {
		private int SIZE;
		private int counter = 0;
		private String name;
		public Counter(int size, String name) {
			this.SIZE = size;
			this.name = name;
		}
		@Override
		public void run() {
			while(this.counter < SIZE) {
				this.counter++;
			}
			System.out.println("done counting," + this.name + "=" + this.counter);
		}
	}
	
	public static void main(String args[]) {
		int size = 1000000;
		Counter counterA = new Counter(size, "CounterA");
		Counter counterB = new Counter(size, "CounterB");
		new Thread(counterA).start();
		new Thread(counterB).start();
	}
}

Outout.Notice the CounterB finishes first even though it was started later. It’s becuase A and B are running concurrently, in this case, it just happens that B finished first. When you run the program again, A might finishes first, or it could be B finishes first again.

done counting,CounterB=1000000
done counting,CounterA=1000000

Search within Codexpedia

Custom Search

Search the entire web

Custom Search