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; = name;
		public void run() {
			while(this.counter < SIZE) {
	public static void main(String args[]) {
		int size = 1000000;
		new Thread(counterA).start();
		new Thread(counterB).start();


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

Search within Codexpedia

Custom Search

Search the entire web

Custom Search