Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I execute a particular block of code inside a method via thread

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 */

    }
}
like image 841
Abhisek Avatar asked Jul 19 '11 07:07

Abhisek


People also ask

Can we call thread inside 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.

Which method is used to write the code to execute as thread?

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.

Can two threads run at the same time?

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.

How do you run a method in a new thread?

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.


2 Answers

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();
    }
}
like image 124
Sergey Aslanov Avatar answered Sep 26 '22 00:09

Sergey Aslanov


yup all you have to do is implement runnable, then call that meathod inside of run()

like image 43
gsfd Avatar answered Sep 27 '22 00:09

gsfd