can I execute a particular block of code inside a method via thread. As for example
Class A{
public void execute(){
/* some code where threading is not required*/
/* block of code which need to execute via thread */
}
}
Yes a thread can launch another thread, and that thread can launch thread(s) and on and on... In the run() method of a thread - you can create and start other threads.
Implementing Runnable interface This is the easy method to create a thread among the two. In this case, a class is created to implement the runnable interface and then the run() method. The code for executing the Thread should always be written inside the run() method.
Within a process or program, we can run multiple threads concurrently to improve the performance. Threads, unlike heavyweight process, are lightweight and run inside a single process – they share the same address space, the resources allocated and the environment of that process.
Java Thread run() methodThe run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed. You can call the run() method multiple times.
class A {
public void execute() {
/* some code where threading is not required*/
new Thread() {
public void run() {
/* block of code which need to execute via thread */
}
}.start();
}
}
yup all you have to do is implement runnable, then call that meathod inside of run()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With