-1

I have made a programe which print 5 number using 2 threads.

public class Class1 {

static int value = 6;
 public void show() {
    for (int i = 0; i < value; value--) {
        System.out.println(Thread.currentThread().getName() + " - Number: " + value);
    }
} 
public static void main(String[] args) {
    final Class1 main = new Class1();

    Runnable runner = new Runnable() {
        @Override
        public void run() {
            main.show();
        }
    };

    new Thread(runner, "Thread 1").start();
    new Thread(runner, "Thread 2").start();
}   }

It gave me output like this:

Thread 1 - Number: 6
Thread 2 - Number: 6
Thread 1 - Number: 5
Thread 2 - Number: 4
Thread 1 - Number: 3
Thread 1 - Number: 1
Thread 2 - Number: 2

But i want that it gave me output like this

Thread 1 - Number: 6
Thread 1 - Number: 5
Thread 1 - Number: 4
Thread 2 - Number: 3
Thread 2 - Number: 2
Thread 2 - Number: 1

I know it is easy we can simply use if else condition in the show() Method but i don't want to use if else in the show() method, i want to change some thing in the main() method which do the work done.

shaun tait
  • 11
  • 4
  • Do you want your second thread to begin only when the first one ends ? – Hearner Jun 26 '18 at 12:39
  • @Hearner i want the out which i show at the last of my post – shaun tait Jun 26 '18 at 12:40
  • @Hearner i want when Thread 1 print 6,5,4 then we lock Thread 1 and then thread 2 print 321 – shaun tait Jun 26 '18 at 12:41
  • 2
    The simplest solution is to use one thread! Anything else is going to look very cumbersome and inefficient. – Peter Lawrey Jun 26 '18 at 12:43
  • @PeterLawrey i know use one thread will solve the problem but its my Uni assignment, i search on internet but unable to do that work. – shaun tait Jun 26 '18 at 12:45
  • Possible duplicate of [is there a 'block until condition becomes true' function in java?](https://stackoverflow.com/questions/5999100/is-there-a-block-until-condition-becomes-true-function-in-java) – Mike Jun 26 '18 at 12:45
  • @PeterLawrey it can be easily done by using if statement in the show() method but they said you can not use if else do all your work in the main method – shaun tait Jun 26 '18 at 12:46
  • @Mike no buddy my question is different one – shaun tait Jun 26 '18 at 12:51
  • The simplest solution is to not call `start()` but call `run()` instead. The problem is the assignment is daft so you end up having to assume requirements which don't make sense. – Peter Lawrey Jun 26 '18 at 12:54
  • @PeterLawrey the queston is simple the Thread 1 should print 6,5,4, then Thread 2 sould print next three integer. What's confusing in that ? – shaun tait Jun 26 '18 at 12:58
  • @shauntait because the simplest solution is to a) not use threads, b) not use a variable, c) not use any kind of co-ordination except via the main thread. Once you start adding code which doesn't do anything useful there is no limit to amount of pointless code you could write. ;) – Peter Lawrey Jun 26 '18 at 13:00

4 Answers4

1

You can wait to start the second thread after first thread has finished, basically you need to synchronize thread execution.

To do that you can:

  • enter in a synchronized block holding the same key
  • using the wait notify keywords on the same lock
  • using the java Lock class
  • using join on first thread to wait that he finishes before starting the second
  • use an Observable to coordinate start of threads

And many others.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
1

Firt thing first. You are not using synchronization in your Threads and if you want to use join() you need to use an if in your run method and

static int value = 6;

Is not thread safe! For better use an AtomicInteger and for control of theads check ExecutorService

Gatusko
  • 2,503
  • 1
  • 17
  • 25
1

You can do it like below:

final int number = 6;
    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            for(int i = 0; i< number/2;i++){
                System.out.println("Thread 1 Number: "+i);
            }
        }
    });
    Thread t2 = new Thread(new Runnable() {

        @Override
        public void run() {
            for(int i = number/2; i< number;i++){
                System.out.println("Thread 2 Number: "+i);
            }
        }
    });
        t1.run();
        t2.run();
mstfyldz
  • 482
  • 1
  • 6
  • 12
  • OK. I have edited for thread2 run after thread 1. I hope this helps. – mstfyldz Jun 26 '18 at 12:58
  • Note: if you replace `start()` with `run()` you don't need join. ;) – Peter Lawrey Jun 26 '18 at 13:01
  • I think the OP needs to make it look like there is multiple threads involved. – Peter Lawrey Jun 26 '18 at 13:41
  • yeah @mstfyldz if there are for example 10 threads then we override run() Method 10 times? – shaun tait Jun 28 '18 at 07:22
  • @mstfyldz i think thats not good approach, what is your opinion abput it? – shaun tait Jun 28 '18 at 07:23
  • So you should give more detail for your requirements for example how to divide number between threads? @shauntait – mstfyldz Jun 28 '18 at 08:05
  • @mstfyldz your solution is perfectly fine, but if we have for example 4 threads then we override the run() method 4 time?? (or there is any other way? i actually dont want to override run() agian and agian) like in the above case we have 2 threads so you override run() method 2 times – shaun tait Jun 28 '18 at 08:44
0
public class PrintHalfNumber {

  public static void main(String[] args) {

    Printer sp = new Printer();

    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.submit(new SecondHalfProducer(sp, 10));
    executor.submit(new FirstHalfProducer(sp , 10));
    executor.shutdown();
  }

}


class Printer {

  Semaphore secondHalf = new Semaphore(0);
  Semaphore firstHalf = new Semaphore(1);

  public void printSecondHalf(int num) {
    try {
        secondHalf.acquire();
    }catch(InterruptedException exception) {

    }
    for(int i = (num/2) + 1 ; i <= num ; i++ ) {
        System.out.println("Thread 2 - Number: " + i);
    }

    firstHalf.release();
  }

  public void printFirstHalf(int num) {
    try {
        firstHalf.acquire();
    }catch(InterruptedException exception) {

    }
    for(int i = 1 ; i <= num/2 ; i++) {
        System.out.println("Thread 1 - Number: " + i);
    }

        secondHalf.release();
  }

}

class SecondHalfProducer implements Runnable {

  Printer sp;
  int index;

  SecondHalfProducer(Printer sp , int index) {
    this.sp = sp;
    this.index = index;
  }

  @Override
  public void run() {
    sp.printSecondHalf(index);
  }
}

class FirstHalfProducer implements Runnable{
  Printer sp;
  int index;

  FirstHalfProducer(Printer sp , int index) {
    this.sp = sp;
    this.index = index;
  }

  @Override
  public void run() {
        sp.printFirstHalf(index);
  }
}

Output of the program is :

Thread 1 - Number: 1

Thread 1 - Number: 2

Thread 1 - Number: 3

Thread 1 - Number: 4

Thread 1 - Number: 5

Thread 2 - Number: 6

Thread 2 - Number: 7

Thread 2 - Number: 8

Thread 2 - Number: 9

Thread 2 - Number: 10
Girish Rathi
  • 129
  • 1
  • 4