Issue
I need to have two threads synchronized such that both cannot run concurrently. Once called, they need to run so if the other thread is running, they need to wait until the other one is done and then run after it. I know I can use join() but my question involves threads in different classes with no reference to each other. Is it a good idea to make the threads static class variables so they both can access each other?
One thread (t1) is called from a method in the Main Activity and the other thread (t2) is inside an AsyncTask:
public class MainActivity extends AppCompatActivity
{
public void someMethod()
{
// code
Thread t1 = new Thread(() ->
{
// run thread code
});
t.start();
try
{
t.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
// someMethod follow-up code
}
}
public class FetchData extends AsyncTask<Void, Void, Void>
{
protected final Void doInBackground(Void... params)
{
// code
Thread t2 = new Thread(() ->
{
// run thread code
});
t.start();
try
{
t.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
// follow-up code
}
}
}
Solution
I executed the synchronization by adding static class thread variables and added a sleep factor so I could test:
public class MainActivity extends AppCompatActivity implements Interface.InterfaceCommon
{
public static Thread t1;
FetchData fetchData;
@Override
protected void onCreate(Bundle savedInstanceState)
{
t1 = new Thread();
fetchData = new FetchData();
}
public void someMethod()
{
Runnable r = () ->
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
/// Some code
};
t1 = new Thread(r);
try
{
FetchData.t2.join();
t1.start();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class FetchData extends AsyncTask<Void, Void, Void>
{
public static Thread t2;
public FetchData()
{
t2 = new Thread();
}
protected final Void doInBackground(Void... params)
{
Runnable r = () ->
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
/// Some code
};
t2 = new Thread(r);
try
{
MainActivity.t1.join();
t2.start();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
Answered By - Samuel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.