Pass arguments to run() in Threading Example
in
Programming Questions
•
2 years ago
The
Threading Example on the Processing wiki is a great resource. I'm curious — where does the
run() method get fired? I'd like to pass arguments to it to change variables within the class. Below is the Threading example modified to do something that I'd like.
—
http://jonobr1.com/
- SimpleThread thread1;
- SimpleThread thread2;
- void setup() {
- size(200,200);
- }
- void initThreads() {
- if(thread1 == null) thread1 = new SimpleThread(1000,"a");
- thread1.start();
- if(thread2 == null) thread2 = new SimpleThread(1200,"b");
- thread2.start();
- // Execute some code here to:
- // Pass variables to run() to change the id and count
- }
- void draw() {
- background(255);
- fill(0);
- int a = thread1.getCount();
- text(a,10,50);
- int b = thread2.getCount();
- text(b,10,150);
- if(thread1.getCount() >= 10 && thread2.getCount >= 10) initThreads();
- }
- class SimpleThread extends Thread {
- boolean running; // Is the thread running? Yes or no?
- int wait; // How many milliseconds should we wait in between executions?
- String id; // Thread name
- int count; // counter
- // Constructor, create the thread
- // It is not running by default
- SimpleThread (int w, String s) {
- wait = w;
- running = false;
- id = s;
- count = 0;
- }
- int getCount() {
- return count;
- }
- // Overriding "start()"
- void start () {
- // Set running equal to true
- running = true;
- // Print messages
- println("Starting thread (will execute every " + wait + " milliseconds.)");
- // Do whatever start does in Thread, don't forget this!
- super.start();
- }
- // We must implement run, this gets triggered by start()
- void run () {
- while(count < 10) {
- countAndPrint(id, count);
- // Ok, let's wait for however long we should wait
- try {
- sleep((long)(wait));
- } catch (Exception e) {
- }
- }
- System.out.println(id + " thread is done!"); // The thread is done when we get to the end of run()
- }
- void countAndPrint(String id, int count) {
- println(id + ": " + count);
- count++;
- }
- // Our method that quits the thread
- void quit() {
- System.out.println("Quitting.");
- running = false; // Setting running to false ends the loop in run()
- // IUn case the thread is waiting. . .
- interrupt();
- }
- }
I could change variables where the red text is. Something like:
- Thread1.id = "d";
- Thread2.id = "e";
- Thread1.count = random(1000);
- Thread2.count = random(1000);
But am just curious if there's another way around it.
—
http://jonobr1.com/
1