0

I'm creating a program that prints the sound of three bells. I need to stop the process when the user types a key on the keyboard, how can I do? Also, I would make sure that every bell show your sound in a random time, making use of the property Math.random(). You can associate a random time to a thread?

package campane;

import java.io.*;
import java.util.*;

public class GestioneCampane extends Thread {

    public static void main(String [] args) {
        BufferedReader tast = new BufferedReader(new InputStreamReader(System.in));

        char pressione;

        Campane campana = new Campane("DIN", 300); 
        Campane campana2 = new Campane("DON", 1000);
        Campane campana3 = new Campane("DAN", 2000);

        campana.start();
        campana2.start();
        campana3.start();


    }
}

this is the second class

package campane;

public class Campane extends Thread {

    private String campane; // word to print
    private int delay;

    public Campane(String whatToSay, int delayTime) {
        campane = whatToSay;
        delay = delayTime;
    }

    public void run() {
        try {
            while(true) {
                System.out.print(campane + " ");
                Thread.sleep(delay); 
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
toniedzwiedz
  • 17,895
  • 9
  • 86
  • 131
user3344186
  • 191
  • 1
  • 3
  • 12
  • So the main question is how to listen for a keypress? Btw your class GestioneCampane doesnt need to extend Thread – JohnnyAW May 25 '14 at 10:45
  • Yes, I want to stop the program by pressing any key on the console. Then, I want to draw the threads in a time randomly generated, I thought Math.random. – user3344186 May 25 '14 at 10:47
  • There is no easy way for listening on keypressed in console for java, you could use KeyBindings like mentioned by Sr. Richenso, but the you have to use Swing. It would be much easier to listen for Key+Enter on the console, if its ok for you – JohnnyAW May 25 '14 at 10:57

1 Answers1

0

You can stop a thread by interrupting it:

Thread.interrupt()

You can stop a thread for a given time, and continue with it after the time is consumed:

Long time = 15000L; // in milliseconds

Thread.sleep(time);

Use KeyBindings to intercept keys pressed and randomize your sound relevence, this example can save time

Community
  • 1
  • 1