6 Replies - 415 Views - Last Post: 23 August 2019 - 04:16 PM Rate Topic: -----

#1 kaiser7511   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 03-March 19

Threads/Multi-Threads

Posted 22 August 2019 - 08:11 PM

This program is suppose to display Ping or Pong(in any order) to the window at least 10 times using threads. Right now it is displaying Ping and Pong in a random order when iterating through the loop. The program runs successfully but, I am trying to figure out how to display ping OR pong(not both) during each iteration of the loop. I was thinking of preventing one of the threads from running if the other has already been selected and, I think I need to implement some sort of random generator to determine which thread should run to display ping or pong, but I cannot figure out how to prevent a thread from running. I have tried to implement locks but it only allowed one iteration before throwing exceptions. Any help is greatly appreciated. Here is my current code.
public class PingPong implements Runnable {

    private final String word;    //flag to hold ping or pong
    private final int length = 10;    //number of times to print
    private boolean selection;    //flag to determine if ping or pong will print
    
    /**
     * constructor accepting String value to assign to selection
     * @param s - String value to assign to selection
     */
    public PingPong(String s) {
        this.word = s;
    }
    
    @Override
    public void run() {
        try {   //if 1 print ping, if 2 print pong
            //print selection (Ping or Pong) each time for the entire length value
            for (int i = 0; i < length; i++) {
                switch (word) {
                    case "Ping":
                        System.out.println(word);
                        break;
                    case "Pong":
                        System.out.println(word);
                        break;
                    default:   //default only breaks so Ping or Pong is only printed
                        break;
                }
                Thread.sleep(1000);   //sleep for 10 seconds

            }
        } catch (IllegalArgumentException ex) {
            System.out.println(ex.getMessage());
        } catch (InterruptedException ex) {
            System.err.println(ex.getMessage());
        }
    }
}






public class PingPongThread {

    public static void main(String[] args) {
        
        //create executor with fixed thread pool of 2 threads
        ExecutorService executor = Executors.newFixedThreadPool(2);
        
        //create thread for Ping and Pong
        executor.execute(new PingPong("Ping"));
        executor.execute(new PingPong("Pong"));
        
        //shutdown the executor thread pool
        executor.shutdown();
        
    } 
}



Is This A Good Question/Topic? 0
  • +

Replies To: Threads/Multi-Threads

#2 xclite   User is offline

  • I wrote you an code
  • member icon


Reputation: 1393
  • View blog
  • Posts: 4,225
  • Joined: 12-May 09

Re: Threads/Multi-Threads

Posted 23 August 2019 - 08:39 AM

Why not remove the entire switch statement, and just always print the word you sent in? You might find that this simplifies the code, since you create a PingPong with "Ping" and with "Pong".
Was This Post Helpful? 0
  • +
  • -

#3 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 781
  • View blog
  • Posts: 5,899
  • Joined: 25-December 13

Re: Threads/Multi-Threads

Posted 23 August 2019 - 09:00 AM

Where does the value of word change while the loop executes? Won't it always be the same?
Was This Post Helpful? 0
  • +
  • -

#4 kaiser7511   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 03-March 19

Re: Threads/Multi-Threads

Posted 23 August 2019 - 10:58 AM

Yes I could remove the switch statement but I will still get the same results as ping and pong still print. I am trying to have ping or pong print on each iteration of the loop. I was trying to implement some sort of flag to only allow one of the threads to print on each iteration of the loop and not both. The value of word does no value of word does not change in the loop as it is set when a new PingPong class is created.
Was This Post Helpful? 0
  • +
  • -

#5 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 781
  • View blog
  • Posts: 5,899
  • Joined: 25-December 13

Re: Threads/Multi-Threads

Posted 23 August 2019 - 12:56 PM

What is the purpose of trying to force threads to be synchronous (ie one after the other)?
The OS executes the code in a thread depending on various resource availabilities. It is possible for the loop in a thread to iterate many times before the OS swaps execution to another thread.
Was This Post Helpful? 0
  • +
  • -

#6 kaiser7511   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 03-March 19

Re: Threads/Multi-Threads

Posted 23 August 2019 - 03:28 PM

I don't need the threads to run one after the other. I need one thread to be completely blocked from running during each loop iteration. Only one thread needs to be allowed to run. Right now, both threads run and print to the screen during each loop iteration.
I updated the code and removed the switch statement but still get the same results.
@Override
    public void run() {
        try {   //if 1 print ping, if 2 print pong
            //print selection (Ping or Pong) each time for the entire length value
            for (int i = 0; i < length; i++) {
                System.out.println(word);   
                Thread.sleep(1000);   //sleep for 10 seconds 
            }
        } catch (IllegalArgumentException | InterruptedException ex) {
            System.out.println(ex.getMessage());
        }
    }

Was This Post Helpful? 0
  • +
  • -

#7 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 781
  • View blog
  • Posts: 5,899
  • Joined: 25-December 13

Re: Threads/Multi-Threads

Posted 23 August 2019 - 04:16 PM

Quote

I need one thread to be completely blocked from running during each loop iteration

Don't start the threads so they run at the same time. Start one and when it ends, start the other one.
Or forget about using threads and just call the methods one after the other.

Can you post an example of the desired output?

This post has been edited by NormR: 23 August 2019 - 05:04 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1