Different ways of multithreading

Hello everyone, I am aware of the use of thread(methodName) in processing for easy multithreading in a sketch, but this implementation of the thread class has limited functionality. You can’t put arguments into the function, and can’t use it on objects unless you create a function that accesses the object to put into the methodName argument of thread(). This would become really inefficient with multiple objects. Is there another way to extend the thread class to allow for similar functionality to thread() while fixing these problems? Extending the thread class may work, but it is kind of complicated to use within processing.

Hi @SNICKRS, it depends on what you’re trying to do, but you can implement the Runnable interface with your class and that would allow you to create custom methods that run on a separate thread. I use this to run a high performance audio thread, so I typically only do it once, but if you manage your threads you can run as many as you like theoretically. The other advantage of Runnable is you can also extend your class to inherit another parent class instead of inheriting the Thread class directly.
I borrowed this code from: Runnable interface in Java - GeeksforGeeks

public class RunnableDemo {
  
    public static void main(String[] args)
    {
        System.out.println("Main thread is- "
                        + Thread.currentThread().getName());
        Thread t1 = new Thread(new RunnableDemo().new RunnableImpl());
        t1.start();
    }
  
    private class RunnableImpl implements Runnable {
  
        public void run()
        {
            System.out.println(Thread.currentThread().getName()
                             + ", executing run() method!");
        }
    }
}
2 Likes