Reputation: 14751
I have a class with name Socket that have tow function for example func1 and func2
fucn1() {
while(true) {
...
}
}
fucn2() {
while(true) {
...
}
}
I want two of them run with thread in a time and concurrently. how can i do that??
class socket implement Runnable {
public void run() {
func1();
func2();
}
}
In this code only first function is executed not second. How can i do for concurrently run both of them?
Upvotes: 0
Views: 2020
Reputation: 25156
My Suggestion is :
Instead of making socket Class
Runnable
,
Create two Runnable
threads as in my example below and call your functions from there. And start these two threads from your Socket
class.
class Socket{
private void startThreads() {
new Thread(new Th1()).start();
new Thread(new Th2()).start();
}
}
class Th1 implements Runnable {
@Override
public void run() {
fucn1();
}
}
class Th2 implements Runnable {
@Override
public void run() {
fucn2();
}
}
Upvotes: 3
Reputation: 62439
You can run them concurrently like this:
// start a thread for func1
Thread t1 = new Thread(new Runnable() {
public void run() {
func1();
}
});
t1.start();
// func2 will run in parallel on the main thread
func2();
t1.join(); // if you want to wait for func1 to finish.
You haven't given any details, so I'm assuming they have no side-effects.
Upvotes: 2
Reputation: 1135
You need to create two threads for this scenario.
class socket implement runable
{
boolean condition;
public socket(boolean condition){
this.condition = condition;
}
public void run()
{
if(condition == true){
func1();
}else{
func2();
}
}
}
Thread t1 = new Thread(new Socket(true));
Thread t1 = new Thread(new Socket(false));
t1.start();
t2.start();
In addition to this you need to yield control in each method just to make sure that every thread will get fair chance to run.
Upvotes: 0
Reputation: 500417
If you want to run the two functions concurrently, spawn two threads and run each function in its own thread.
That's precisely what threads are for.
Upvotes: 0