简体   繁体   中英

How to run java threads sequentially on Android

I have seven sonar sensors and I aim to display these sensor values sequentially on an Android tablet.

To dynamically display the sensor values on the tablet screen, I used Runnable s.

However, if the sonar sensors work in parallel, it causes interference between sonar sensors. Therefore, I need to make them work sequentially.

My question is : is it possible to use threads sequentially to display sensor values on an Android Tablet?

Although I used join() and sleep() , still the sensors are interfering with each other. When I tried to use wait and notify, the application gives an out of memory exception. I also tried to use synchronized methods but it didn't affect it.

Below you can see my code.

package com.dinning;

import android.widget.TextView;

public class Dinning implements Runnable 
{
    public Interfacekit diningkit;
    public TextView[] Rfidviews; 
    int count=1;

    public Dinning(Interfacekit diningkit,Rfid drfid1,Rfid drfid2, Rfid drfid3,Rfid drfid4,Rfid drfid5,Rfid drfid6,Rfid fsrfid1,Rfid fsrfid2,Rfid fsrfid3,final TextView[] Rfidviews)
    {
        this.diningkit = diningkit;
        this.Rfidviews = Rfidviews;
        new Thread(this).start();
    }

    public void run()       
    {
        while(count==1)
        {   
            if(diningkit.getattach()==true)
            {
                Thread t1 = new Thread(new Runnable() 
                {  
                    public void run() 
                    {
                        Rfidviews[11].post(new Runnable() 
                        {
                            public void run() 
                            {
                                {
                                    int sonar0 = diningkit.getsonar(7);
                                    if(sonar0!=0)
                                        Rfidviews[11].setText("Port0:"+sonar0);
                                    else
                                        Rfidviews[11].setText(" ");
                                }            
                            }
                        });
                    }
                });

                Thread t2 = new Thread(new Runnable() {  
                    public void run() {
                        Rfidviews[12].post(new Runnable() 
                        {
                            public void run() 
                            {
                                {
                                    int sonar1 = diningkit.getsonar(6);
                                    if(sonar1!=0)
                                        Rfidviews[12].setText("Port1:"+sonar1);
                                    else
                                        Rfidviews[12].setText(" ");
                                }            
                            }
                        });
                    }
                });

                Thread t3 = new Thread(new Runnable() 
                {  
                    public void run() 
                    {
                        Rfidviews[13].post(new Runnable() 
                        {
                            public void run() 
                            {
                                {
                                    int sonar2 = diningkit.getsonar(5);     
                                    if(sonar2!=0)
                                        fidviews[13].setText("Port2:"+sonar2);
                                    else
                                        Rfidviews[13].setText(" ");
                                }        
                            }
                        });
                    }       
                });

                t1.start();
                t2.start();
                t3.start();
            } 
        }//while        
    }           
}





 package com.dinning;



import android.app.Activity;
import android.content.Context;
import com.phidgets.InterfaceKitPhidget;
import com.phidgets.Phidget;
import com.phidgets.PhidgetException;
import com.phidgets.event.AttachEvent;
import com.phidgets.event.AttachListener;
import com.phidgets.event.DetachEvent;
import com.phidgets.event.DetachListener;
import com.phidgets.event.InputChangeEvent;
import com.phidgets.event.InputChangeListener;
import com.phidgets.event.SensorChangeEvent;
import com.phidgets.event.SensorChangeListener;

public class Interfacekit {

    int status=1;
    InterfaceKitPhidget ik;
    public boolean attach = false;
    public Phidget phidget;
    int value = 0;
    int index = 0;
    int serial;

    int value0,value1,value2,value3,value4,value5,value6,value7,valport;
    int sonarvalue0,sonarvalue1,sonarvalue2,sonarvalue3,sonarvalue4,sonarvalue5,sonarvalue6,sonarvalue7;
    int curVal;

    public Interfacekit(final Context con,final Activity act,int serial)
    {
        this.serial = serial;

        try
        {
            com.phidgets.usb.Manager.Initialize(con);
            ik = new InterfaceKitPhidget();



            ik.addAttachListener(new AttachListener() {
                public void attached(final AttachEvent ae)
                {
                    act.runOnUiThread(new Runnable() {

                        public void run() {
                            try{
                            attach=true;    

                            value0= ik.getSensorValue(0);
                            value1= ik.getSensorValue(1);
                            value2= ik.getSensorValue(2);
                            value3=ik.getSensorValue(3);
                            value4=ik.getSensorValue(4);
                            value5= ik.getSensorValue(5);
                            value6= ik.getSensorValue(6);
                            value7= ik.getSensorValue(7);


                            }catch(Exception e){}
                        }

                    });




                }
            });



            ik.addDetachListener(new DetachListener() {
                public void detached(final DetachEvent ae) {

                    attach = false;
                    phidget = ae.getSource();
                    act.runOnUiThread(new Runnable() {

                        public void run() {

                        }
                    });
                }
            });


            ik.addSensorChangeListener(new SensorChangeListener() {
                public void sensorChanged(SensorChangeEvent se) {  //final Sensorchangeevent


                    value = se.getValue();
                    index = se.getIndex();



                    try {

                        sonarvalue0=ik.getSensorValue(0);
                        sonarvalue1=ik.getSensorValue(1);
                        sonarvalue2=ik.getSensorValue(2);
                        sonarvalue3=ik.getSensorValue(3);
                        sonarvalue4=ik.getSensorValue(4);
                        sonarvalue5=ik.getSensorValue(5);
                        sonarvalue6=ik.getSensorValue(6);
                        sonarvalue7=ik.getSensorValue(7);





                    } catch (PhidgetException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }









                }



            });




            ik.addInputChangeListener(new InputChangeListener() {
                public void inputChanged(final InputChangeEvent ie) {



                }
            });
            ik.open(serial);

        }
        catch(Exception e){}
    }



        public boolean getattach()
        {

         return attach ;    
        }

        /* Sonar*/

        public int getsonar(int digitalOutput){

            int curVal,result = 0;


            if(5==digitalOutput){



                    try {
                        ik.setOutputState(digitalOutput, true);

                    } 
                    catch (PhidgetException e) {

                    e.printStackTrace();
                    }



                    curVal=(int) (1.296*sonarvalue2);

                    if(curVal>0 && curVal<60){
                        result=curVal;
                        System.out.println("Port2: "+result);
                    }
                    else if (curVal>60)
                        result=0;



            }

            else if(6==digitalOutput){



                try {
                    ik.setOutputState(digitalOutput, true);

                } 
                catch (PhidgetException e) {

                e.printStackTrace();
                }



                curVal=(int) (1.296*sonarvalue1);

                if(curVal>0 && curVal<80)
                    result=curVal;

                else if(curVal>80) 
                    result=0;



            }


            else if(7==digitalOutput){



                try {
                    ik.setOutputState(digitalOutput, true);

                } 
                catch (PhidgetException e) {

                e.printStackTrace();
                }



                curVal=(int) (1.296*sonarvalue0);

                if(curVal>0 && curVal<50)
                    result=curVal;

                else if(curVal>50)
                    result=0;



            }

            return result;

    }





        /* End Sonar*/



}

Use ExecutorService in java.util.concurrent package. In particular Executors.newSingleThreadExecutor();

newSingleThreadExecutor

public static ExecutorService newSingleThreadExecutor() Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially , and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.

Also

t1.start();
t1.join();
t2.start();

etc. Start one when the other dies. However I don't see the need for threads at all. Needless complication and against the design purpose of them?

Instead of

Thread t1 = new Thread(new Runnable() {  
                public void run() {
                   //do something
                }
            });

which runs the run() method in a thread.

Try

(new Runnable() {  
    public void run() {
        //do something
    }
 }).run();

which creates the anonymous Runnable and calls its run() directly (rather than via a Thread ), and is hence executed sequentially.

Edit 0 : You seem to have lots of Thread s and Runnable s for no clear reason. I believe this code should be equivalent, but simplifies away a lot of the Thread s and Runnable s that make it confusing to read:

package net.ukims.dsp.cid.dataaccess;

import android.widget.TextView;

public class Dinning implements Runnable {
    public Interfacekit diningkit;
    public TextView[] Rfidviews;
    int count = 1;

    public Dinning(Interfacekit diningkit, Rfid drfid1, Rfid drfid2,
            Rfid drfid3, Rfid drfid4, Rfid drfid5, Rfid drfid6, Rfid fsrfid1,
            Rfid fsrfid2, Rfid fsrfid3, final TextView[] Rfidviews) {
        this.diningkit = diningkit;
        this.Rfidviews = Rfidviews;
        run();
    }

    public void run() {
        while (count == 1) {
            if (diningkit.getattach() == true) {
                Rfidviews[11].post(new Runnable() {
                    public void run() {
                        {
                            int sonar0 = diningkit.getsonar(7);
                            if (sonar0 != 0)
                                Rfidviews[11].setText("Port0:" + sonar0);
                            else
                                Rfidviews[11].setText(" ");
                        }
                    }
                });

                Rfidviews[12].post(new Runnable() {
                    public void run() {
                        {
                            int sonar1 = diningkit.getsonar(6);
                            if (sonar1 != 0)
                                Rfidviews[12].setText("Port1:" + sonar1);
                            else
                                Rfidviews[12].setText(" ");
                        }
                    }
                });

                Rfidviews[13].post(new Runnable() {
                    public void run() {
                        {
                            int sonar2 = diningkit.getsonar(5);
                            if (sonar2 != 0)
                                fidviews[13].setText("Port2:" + sonar2);
                            else
                                Rfidviews[13].setText(" ");
                        }
                    }
                });             
            }
        }// while
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM