Threads Question
in
Programming Questions
•
7 months ago
Have read lot now about Java threading but have a question about a method that seems to work that I haven't seen as an example anywhere, so is what I am doing here OK? I basically want to have a thread run just once whenever a button is clicked, and the code below does this, but is my approach of re-instantiating the thread every time the mouse is clicked OK? I assume that when run() completes the thread ends and system resources are automatically released, so re-instantiating isn't a problem?
|Thanks
Mark
- SimpleThread thread1;
- Button startThread1Button, stopThread1Button ;
- void setup() {
- size(600,400);
- startThread1Button = new Button(10,10, 60, 40, "thread1");
- stopThread1Button = new Button(100,10, 60, 40, "stop1");
- thread1 = new SimpleThread("thread1");
- }
- void draw() {
- background(255);
- startThread1Button.display();
- stopThread1Button.display();
- }
- class SimpleThread extends Thread {
- boolean running;
- int counter;
- String threadName;
- // Constructor
- SimpleThread (String _threadName) {
- running = false;
- counter = 0;
- threadName=_threadName;
- }
- void start () {
- running = true;
- println("Starting thread...");
- super.start();
- }
- void run () {
- running = true ;
- while (running) {
- println("Thread " + threadName + " has run " + counter + " times");
- counter++;
- delay(1000);
- }
- println("Thread is done..."); // The thread is done when we get to the end of run()
- quit();
- } // end run()
- void quit() {
- println("Quitting...");
- running = false; // ends the loop in run()
- }
- }
- class Button {
- //Variables
- int x, y, w, h;
- String label;
- int colour;
- boolean activeState;
- //Constructor
- Button (int _x, int _y, int _w, int _h, String _l) {
- x=_x;
- y=_y;
- w=_w;
- h=_h;
- label =_l;
- }
- //Methods
- void display() {
- fill(255);
- rect(x, y, w, h);
- fill(125);
- rect(x+2, y+2, w-4, h-4);
- fill(0);
- textAlign(CENTER, CENTER);
- text(label, x, y, w, h);
- }
- boolean over() {
- if (mouseX > x && mouseX < x+w && mouseY > y && mouseY < y+h) {
- return true;
- }
- else {
- return false;
- }
- } //end of over() method
- } //end of class Button
- void mousePressed() {
- if (startThread1Button.over()) {
- if (thread1.running == false) {
- thread1 = new SimpleThread("thread1");
- thread1.start();
- }
- }
- if (stopThread1Button.over()) {
- thread1.quit();
- }
- } // end mousePressed()
1