Threads

Threads in Android are divided to two categories :

1) UI Thread

2) Worker Thread


UI Thread

UI Thread is the thread of your main activity in which your application starts and run other routines to initialize or perform othe operations,you can even get into  UI Thread while you are out of main activity context by using runOnUIThread(Rannable action) which is a member of Activity class , this situation may happen when you are in a  non-UI Thread , a Broadcast Receiver ….etc .Sometime we are using some async tools like AsyncTask or Services … that are partially or completely runs on UI Thread , Service is a good example of a task which run on main UI Thread ,The AsyncTask which is designed for running asynchrounous short operation,on the other hand has in fact several parts , its  doInBackground method works actually on a non-UI Thread while onPreExecute & onProgressUpdate and onPostExecute runs on UI Thread.


Worker Thread

The main focus of this topic is about discussing worker threads , a Worker Threads is a Thread performing background operations in a separated non-UI Thread , so attempt to update UI from it is not allowed and system raise an exception , this is a place only to run your calculation tasks.Ofcourse you still are able to communicate the result and status to main activity in which the necessary UI update will be done.You can run a thread in an anonymous way like:

Thread thread = new Thread(runnable){

public void run(){}

//to do calculation

};

thread.start();


or simply :

new Thread(runnable){

public void run(){}

//to do calculation

}.start();


or as a Thread subclass:

class MyThread extends Thread{

    @override 
    public void run(){

         //to do calculation

     }

}


Another constructor of Thread takes a runnable object as argument so you can also initialize Thread class by passing a Runnable object

Runnable runnable = Runnable(){

@override 
    public void run(){

         //to do calculation

     }

}

Then :

Thread thread = Thread(runnable);
thread.start();


Synchronization 

Synchronization of threads is one of the most important things developers should care about , there are a few way to achieve properly it.

Locks:
 In Java every object have an implicite lock associated with it ,in Android Documentation we have Locks defined as below

Lock l = ...;
 l
.lock();
 
try {
   
// access the resource protected by this lock
 
finally {
   l
.unlock();
 
}}

When we use synchronized keyword in a statement , in reality we acquire an implicite lock , for example suppose we have two Threads , Thread1,Thread2 which perform some sort of operation on a LinkedList

LinkedList mList;

class Thread1 extends Thread{

    @override 
    public void run(){

         //to do calculation

        mList.add(….)

     }

}

class Thread2 extends Thread{

    @override 
    public void run(){

         //to do calculation

        mList.add(….)

     }

}

As a LinkedList is not a Safe thread object we may faces unexpected results by running those threads , in this case we may fix the issue with synchronized keyword as:

Object object = new Object();

class Thread1 extends Thread{

    @override 
    public void run(){

         //to do calculation

      synchronized(object){       

          mList.add(….)

         }

     }

}

class Thread2 extends Thread{

    @override 
    public void run(){

         //to do calculation

      synchronized(object){       

          mList.add(….)

         }

     }

}


By this way we acquire implicitly a lock object (object in this case) , when Thread1 is executing It will lock on object , and Thread2 is automatically block executing , then once operation finish in run method , Thread2 executes in turn.
Notice : Immutable objects don’t need lock


synchronized method:
 In synchronized method is an automatic implicite lock on the object exposing the method , for example in a class A

class A {

long count = 0

    public void A(long count){

     this.count = count

     }

   public synchronized increaseCount(){

    this.count++;

   }

}



Threads:In Android threads are either UI or no UI


NO UI:
new Thread(new Runnable()

    {

            public void run()

        {

//cannot access UI

        }

    }).start();



UI threads:

Activity.runOnUiThread(Runnable)

View.post(Runnable)

View.postDelayed(Runnable, long)

simple example:

 new Thread(new Runnable()

    {

        public void run()

        {

            view.post(new Runnable()

            {

                public void run()

                {

                    view.setBackground(R.drawable.xxx);

                }

            });

        }});



but for more control on thread , UI with shake handing function between main UI and threads which is more convenient best way is to use AsyncTask (when need to interact with user)

class DownloadPictures extends AsyncTask<String, Void,List> {

        protected List doInBackground(String ...url) //this method executes on worker thread

        {

//calculation NO UI

            return  list; //returned value will be delivered to onPostExecute

        }

        protected void onPostExecute( Bitmap bitmap)

        {

//UI access

        }

    }



**insert , delete,update... methodes of a ContentProvider executes in a bunch of pool threads in process not UI threads

**Important : when your activity restarts in an unexpected way for any reason and one of enoying one when change in orientation that's an issue  for your worker threads !



======================


1_Synchronized method 2_Synchronized statement

************************************************************

Synchronize of two threads on an object (class SynDemo)

public class SeekBarActivity extends Activity {

    /** Called when the activity is first created. */

    SeekBar seek;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        SynDemo d=new  SynDemo();

        Thread1 th=new Thread1(d);

        Thread2 th2=new Thread2(d);

        

        th.start();

        th2.start();

    }

    

    private class Thread1 extends Thread{

        private SynDemo d;

        public Thread1(SynDemo sDemo) {

            d=sDemo;

        }

        @Override

        public void run() {

            super.run();

            d.printNumber("Thread1");

        }

      }

    

    private class Thread2 extends Thread{

        

        private SynDemo d;

        public Thread2(SynDemo sDemo) {

            d=sDemo;

        }

        @Override

        public void run() {

            super.run();

            d.printNumber("Thread2");

        }

    }

    private class SynDemo {

///quickly when system sees this word 'synchronized" it acquire a intrinsic Lock for it! when methode return, it is automatically release

        

        synchronized void printNumber(String string){

            for(int i=0;i<2000;i++){

                Log.i(""+string,String.valueOf(i));

            }

        }

    }

    }



*****************************************************************

wait on an object will release lock on object so allowing other threads to access it which were previously in waiting line

Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:

Deadlock: block situation in which two or more threads are waiting to access an object bu lock not released or...!





class parent

{

static class A

{

public A(){}

public synchronized void methodA()

{

doSomeProcess();



}

public synchronized void doSomeProcess()

{


}

}


......

A a=new A()

A b=new A()

Thread thA=new Thread()

{

    @Override

    public void run() {

        b. methodA();

    }

};


thread.start();




Thread thB=new Thread()

{

    @Override

    public void run() {

        a. methodA();

    }

};


thread.start();


}

 © Xosrov 2016