Java-Multithreading

Method 1: Using Thread class

	class Threading {
	    public static void main(String[] args) {
	        /*Method No.1*/
			Counter ctr = new Counter();
	        ctr.start();
	    }
	}

	/*Method No.1*/
	class Counter extends Thread {
	    public void run() {
	        int ctr = 1;
	        while (ctr <= 10) {
	            System.out.println(ctr++);
	            try {
	                sleep(1000);
	            } catch (InterruptedException ex) {}
	        }
	    }
	}

Method 2: Using Runnable interface

	class Threading {
	    public static void main(String[] args) {
	        /*Method No.2*/
	        Thread thread = new Thread(new Counter());
	        thread.start();
	    }
	}

	/*Method No.2*/
	class Counter implements Runnable {
	    public void run() {
	        int ctr = 1;
	        while (ctr <= 10) {
	            System.out.println(ctr++);
	            try {
	                Thread.sleep(1000);
	            } catch (InterruptedException ex) {}
	        }
	    }
	}
comments powered by Disqus