Question: How to fix my code so that it has 5 threads that count down from 50 to 0 without repetition of numbers? public class Counter{
How to fix my code so that it has 5 threads that count down from 50 to 0 without repetition of numbers?
public class Counter{
private int counter=50; Counter(){ System.out.println("Main Thread START"); MyThread t1 = new MyThread("Thread 1"); MyThread t2 = new MyThread("Thread 2"); MyThread t3 = new MyThread("Thread 3"); MyThread t4 = new MyThread("Thread 4"); MyThread t5 = new MyThread("Thread 5"); t1.start(); try{ Thread.sleep(500); } catch(InterruptedException ie){ } t2.start(); t3.start(); t4.start(); t5.start(); try{ t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); } catch(InterruptedException ie){ System.out.println(ie); } System.out.println("Main Thread END"); } public static void main(String[] args){ new Counter(); } class MyThread extends Thread{ String name=""; public MyThread(String name){ this.name = name; } @Override public void run(){ for(int i=50;i>=0;i--){ try{ Thread.sleep(1000); } catch(InterruptedException ie){ System.out.println(ie); } System.out.println(this.name +" "+ counter); counter--; } } } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
