java - Resetting a new thread repetitively -
in program, there button, "display", , button, "reset". user enters number of prime numbers want in text field , clicks "display" button. then, first x prime numbers appear in text area.
in code, have: declarations:
thread go; thread newthread; jlabel howmanylabel; jtextfield howmany; jbutton display; jbutton reset; jtextarea primes;
action event:
public void actionperformed(actionevent event) { object source = event.getsource(); if (source == display) { display.setenabled(false); if (go == null) { go = new thread(this); go.start(); } else { newthread = new thread(this); newthread.start(); } } else if (source == reset) { display.setenabled(true); howmany.settext(" "); primes.settext(" "); } }
run method:
public void run() { int quantity = integer.parseint(howmany.gettext()); int numprimes = 0; int candidate = 2; // candidate = number might prime primes.append("first " + quantity + " primes:"); while(numprimes < quantity) { if (isprime(candidate)) { primes.append(candidate + ", "); numprimes++; } candidate++; } }
the run() method in same class, , calculates first x amount of prime numbers.
i trying create new thread every time "reset" button called. thread runs first time, not run again after click "reset". can run() method work once?
thanks in advance.
the run()
method other method , can invoked number of times. method cannot invoked multiple times start()
(according thread
).
your explanation not seem fit code gave. want spawn new thread when user clicks reset, yet construct or start threads if source display. did mean, rather, want cancel last thread , enable controls user start again? in case should use future
, not generic thread.
another thing ui components not thread-safe. swing explicitly warns against on every components javadoc. may seeing components not updating visible state when changed different thread. have tried using debugger see if thread not getting spawned, or being spawned, not having result want?
Comments
Post a Comment