java multi-threading thread demo

Multi threading is to spin up multiple threads to do stuff concurrently, each tread contains one running task. In java, there is a Thread class you can extend from and override its run method to do your custom task. The example below demonstrates the basic usage of extending the Tread class.

public class ThreadDemo{
	public static class Counter extends Thread {
		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