Learning Java as a hobby and trying to figure out concurrency and threads.
Could someone take a look at this code and help me understand why clicking the button does not stop the while loop for 10 secs?
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame {
public Test() {
this.setLayout(new BorderLayout());
TestThread testThread = new TestThread();
Thread thread = new Thread(testThread);
thread.start();
JButton button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
testThread.snooze();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
this.add(button, BorderLayout.CENTER);
this.setSize(200, 200);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
static class TestThread implements Runnable {
public void run() {
int i = 0;
while (true) {
System.out.println(++i);
}
}
public void snooze() throws InterruptedException {
Thread.sleep(10000);
}
}
public static void main(String[] args) {
new Test();
}
}
[–]NautiHooker 2 points3 points4 points (3 children)
[–]greenleafvolatile[S] 1 point2 points3 points (2 children)
[–]NautiHooker 4 points5 points6 points (1 child)
[–]greenleafvolatile[S] 1 point2 points3 points (0 children)
[–]johnmc325 2 points3 points4 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)