Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to use Runnable interface to develop multi-threaded Java programs?

public class CountDown {
	// A Java code that creates 5 parallel tasks
	// performing countdown from 5 to 0
	public static void main(String[] args) {
		CountDown application = new CountDown();
		application.start();	
	}
	// Method for spawning 5 parallel threads of execution
	public void start() {
		for(int i=1; i<=5; i++)
			new Thread(new CountDownHandler(5, i)).start();
	}
	// Utility class for handling count down per thread
	// that implements the Runnable interface
	private class CountDownHandler implements Runnable {
		private int id;
		private int counter;
		public CountDownHandler(int counter, int id) {
			this.counter = counter;
			this.id = id;
		}
		public String status() {
			return "id#" + id + " " +
			((counter >= 0) ? counter : "LiftOff!");
		}
		public void run() {
			while(counter >= -1) {
				System.out.println(status());
				counter--;
				try {
					Thread.sleep(1000);
				} catch(Exception e) {

				}
			}
		}
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: wait random time java 
Java :: find minimum number in array java 
Java :: java hashmap key exists 
Java :: how to check the lines in a file java scanner 
Java :: java stream min 
Java :: how to find the sum of an array in java 
Java :: swing setbounds 
Java :: How to remove backstack fragment 
Java :: select in selenium java 
Java :: volatile in java 
Java :: comparable on a generic class java 
Java :: how to get the average from a list in java 
Java :: upload byte array to oss 
Java :: start new activity android 
Java :: java variable in string 
Java :: android list[index] 
Java :: java replace character in string 
Java :: reading from a text file in java 
Java :: json to hashmap java stream 
Java :: check if string is uuid 
Java :: Index through 2d array 
Java :: create new empty list java 
Java :: java button size 
Java :: Java print class type 
Java :: javafx text wrapping 
Java :: switch case java with char 
Java :: arrays.aslist 
Java :: java time difference 
Java :: android java listview clean 
Java :: how to fill a 2d array in java 
ADD CONTENT
Topic
Content
Source link
Name
7+7 =