java - 如何在 Android 上顺序运行 java 线程

标签 java android

我有七个声纳传感器,我的目标是在 Android 平板电脑上按顺序显示这些传感器值。

为了在平板电脑屏幕上动态显示传感器值,我使用了 Runnable

但是,如果声纳传感器并联工作,则会造成声纳传感器之间的干扰。因此,我需要让它们按顺序工作。

我的问题是:是否可以按顺序使用线程在 Android 平板电脑上显示传感器值?

尽管我使用了 join()sleep(),传感器仍然相互干扰。当我尝试使用等待和通知时,应用程序给出内存不足异常。我也尝试过使用同步方法,但它并没有影响它。

下面你可以看到我的代码。

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



}

最佳答案

使用 java.util.concurrent 包中的 ExecutorService。特别是 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.

还有

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

等当另一个死亡时开始一个。但是我根本看不到线程的必要性。不必要的复杂化并违背了它们的设计目的?

关于java - 如何在 Android 上顺序运行 java 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13936969/

相关文章:

java - org.apache.hadoop.mapreduce 未找到 - Hadoop

java - Log4j2 用零填充文件名

java - JSONException : Value &lt;! java.lang 类型的 DOCTYPE 无法转换为 JSONObject

java - 在数组中搜索值并获取数组名称

android - 使用方向键在同一 fragment 中的 LinearLayouts 之间移动焦点/导航

android - firebase 访问 token 将在 4 到 5 小时后过期

Android Studio,不匹配支持库版本错误,但不知道它在哪里指定

java - 当我在 install4j 中使用相对路径,然后在该相对路径上使用 getCanonicalPath() 方法时,它返回错误的绝对路径?

java - 布局更改可见性

android - Cordova 错误 : Failed to fetch platform cordova-android//Error: cmd: Command failed with exit code ENOENT