I would treat the single run execution as a static method. But first I have to show you the old way. It is only puzzling at first because we have to think like 2 class interacting:
class Account {
private int balance = 0;
synchronized void deposit( float amount) {
deposit += amount;
}
class Customer extends Thread {
Account account;
Customer(Account account){
account = account;
}
public void run() {
try{
account.deposit(105f);
}
catch(Exception e) {
e.priintStackTrace;
}
}
Then, in JFrame, when you make the GUI:
Customer c = new Customer( );
only ONE instance can run with that JFrame.
=============
Because of Swing. Swing is always "animating" the widgets. Ex. the modern thread, the only thing in JFrame main():
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
the creation method in JFrame, note we already have a core, central thread running:
private static void createAndShowGUI() {
// System.out.println("Created GUI on EDT? "+
// SwingUtilities.
//isEventDispatchThread());
Account account = new Account();
JFrame f = new JFrame("Swing Paint Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new Customer( account );
f.setSize(250,250);
f.setVisible(true);
}
which leads to a new, modern Customer class. Instead of run():
Runnable code = new Runnable() {
public void run() {
account.deposit(105f);
}
};
// look to the thread in main()
if(SwingUtilities.
isEventDispatchThread()) {
code.run();
} else {
SwingUtilities.
invokeLater(code);
}
================
thread is the only way I know to Synchronize, but the older code technique could lead to a lock, which is impossible to untangle with edits.
Maybe someone else knows a shorter and perhaps cleaner code implementation for running only one instance of your class. The keyword here is running, not static.