maybe someone can help me- in an applet I declared instances of two threads, started them, and made a "stop" button that declares them null. In the thread classes, I made a while (this != null), and the threads are still running after i hit the button.
Here is the init method of the applet:
public void init(){
System.out.println("hi");
setSize(400,200); // make the applet size big enough for our soup bowl
s = new Soup(); // instantiate the Soup
p1 = new Producer(this, s); // declare and instantiate one producer thread - state of NEW
c1 = new Consumer(this, s); // declare and instantiate one consumer thread - state of NEW
p1.start(); // start the producer thread
c1.start(); // start the consumer thread
Button stop = new Button("Stop");
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
p1 = null;
c1 = null;
s.getContents().clear();
}
});
add(stop);
}
and here are the run methods of the threads:
public void run() {
String c;
try {
while (this != null) { // only put in 10 things so it will stop
System.out.println("thikns producer != null");
c = String.valueOf(alphabet.charAt((int)(Math.random() * 26))); // randomly pick a number to associate with an alphabet letter
soup.add(c); // add it to the soup
System.out.println("Added " + c + " to the soup."); // show what happened in Console
bowlView.repaint(); // show it in the bowl
sleep((int)(Math.random() * 2000)); // sleep for a while so it is not too fast to see
}
} catch (InterruptedException e) {
this.interrupt();
}
}
and this:
public void run() {
System.out.println(soup.shouldConsume);
String c;
try {
while(this != null) { // stop thread when know there are no more coming; here we know there will only be 10
c = soup.eat(); // eat it from the soup
System.out.println("Ate a letter: " + c); // show what happened in Console
bowlView.repaint(); // show it in the bowl
sleep((int)(Math.random() * 3000)); // have consumer sleep a little longer or sometimes we never see the alphabets!
}
} catch (InterruptedException e) {
this.interrupt();
}
}
any ideas why this is not working? Any input is appreciated! Thanks everyone!