-1

I have to print the numbers between one to ten , with ten threads and they got to be consecutive numbers. I mean Thread0 - 10 print 1,1,1,1,1,1,1,1,1,1 then Thread 0-10 print 2,2,2,2,2,2,2,2,,2,2

class A extends Thread {
    String name = "";
    static Integer num = 1;

    public void run() {
        for(int i = 0 ; i < 10 ; i++) {
            synchronized (num) {
                num++;
                System.out.println(name + " " + num);
            }

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
        }
    }
}

public static void main(String args[]) {
    for (int i = 0; i < 10; i++) {
        A t1 = new A();
        t1.name = "Thread " + i;
        t1.start();
    }
}

I am trying this but it doesn't work

I tried to use the code above and one more attempt but i print the numbers from 1-10 but with one thread i mean Therad0 - 1,2,3,4,5,6,7,8,9,10 and Thread1 - 1,2,3,4,5,6,7,8,9,10

Filburt
  • 17,626
  • 12
  • 64
  • 115
  • It is unclear what you want the output to be. And do you care (and why) in what order the threads are executed as long as the output is correct? – WJS Mar 20 '23 at 15:47
  • @WJS, This question is a variation on a typical homework assignment. I don't know where the original came from, but it's pernicious. Teaches the kids how to use multiple threads to do something that would be done much better by a single thread. – Solomon Slow Mar 20 '23 at 18:19
  • The order is not important , just 10 threads first to print 1 , then 10 threads to print 2 and so on.. – Slavi Donchev Mar 21 '23 at 08:08

1 Answers1

-1
class Count extends Thread{
String name = "";
public Integer num = 0;
public void run() {
        for(int i = 0 ; i < 10 ; i++) {
            try{
                Count.sleep(500);
            synchronized(num) {
                num++;
                System.out.println(name + ": " + num);

            }
        }catch(InterruptedException e){
            e.printStackTrace();
            }
        }
        }
public static void main(String args[]) {
    for (int i = 0; i < 10; i++) {
        Count t1 = new Count();
            t1.name = "Thread " + i;
            t1.start();
        }
    }

}

  • This is the answear i figured it out – Slavi Donchev Mar 21 '23 at 08:31
  • Now i need to make the same thing but not with sleep.I have to use wait() and notify() any ideas ? – Slavi Donchev Mar 21 '23 at 12:55
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 25 '23 at 21:37