multithreading - Having Some Problems with Threads on Java -
i've got programme of computing prime numbers. when pressing stop programme stops computing prime numbers when press go need programme go on computations, couldn't find out how can start thread again. tried creating new instances of nil happened. here's code:
public class primeapp1 extends jframe { protected jtextarea output; protected jbutton go; protected jbutton stop; protected long counter = 2; protected boolean stopcomputation = false; public boolean run = true; protected boolean isprime(long number) { long max = (long) math.sqrt(number) + 1; (long = 2; < max; i++) { if ((number % i) == 0) { homecoming (false); } } homecoming (true); } public class printprimes extends thread { @override public void run() { // todo auto-generated method stub int primecount = 0; while (run == true) { if (isprime(counter)) { primecount++; output.append(long.tostring(counter) + "\n"); stop.setenabled(true); } counter++; } } } public primeapp1() { super("prime numbers"); final printprimes print = new printprimes(); jpanel content = new jpanel(); borderlayout contentlayout = new borderlayout(); content.setlayout(contentlayout); output = new jtextarea(); output.seteditable(false); jscrollpane scroller = new jscrollpane(output); content.add(scroller, borderlayout.center); jpanel buttonpane = new jpanel(); flowlayout buttonpanelayout = new flowlayout(); buttonpane.setlayout(buttonpanelayout); go = new jbutton("go"); stop = new jbutton("stop"); stop.setenabled(false); buttonpane.add(go); buttonpane.add(stop); content.add(buttonpane, borderlayout.south); go.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { print.start(); } }); stop.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { run = false; } }); setcontentpane(content); setdefaultcloseoperation(jframe.exit_on_close); setsize(600, 600); setvisible(true); } public static void main(string[] args) { new primeapp1(); }
}
i think problem trying start thread has finished processing. can ever start thread once, see here details.
rather starting thread in go action listener, perhaps want create new thread object in actionlistener , start that.
something this:
go.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { printprimes print = new printprimes(); print.start(); } });
rather creating final thread object in constructor.
java multithreading
No comments:
Post a Comment