Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/199.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从锁定机制锁定UI线程更新片段中的ListView_Java_Android_Multithreading_Listview - Fatal编程技术网

Java 从锁定机制锁定UI线程更新片段中的ListView

Java 从锁定机制锁定UI线程更新片段中的ListView,java,android,multithreading,listview,Java,Android,Multithreading,Listview,我有一个列表视图,我想用来自蓝牙插座的消息更新它。ListView是一个片段,这并不重要。 当我想要监听来自套接字的传入消息时,问题就出现了。套接字是一个单独线程上的锁定机制,并用收到的message.FChat.java更新ListView 所以,这感觉就像它完全阻塞了UI线程,所以我猜RunNuithRead它阻塞了UI线程。 如果我把挡块拿出来 字符串reply=bluetoothConnector.readSingleMessage;并将其替换为String reply=test。它工作

我有一个列表视图,我想用来自蓝牙插座的消息更新它。ListView是一个片段,这并不重要。 当我想要监听来自套接字的传入消息时,问题就出现了。套接字是一个单独线程上的锁定机制,并用收到的message.FChat.java更新ListView

所以,这感觉就像它完全阻塞了UI线程,所以我猜RunNuithRead它阻塞了UI线程。 如果我把挡块拿出来 字符串reply=bluetoothConnector.readSingleMessage;并将其替换为String reply=test。它工作正常,UI已更新,似乎工作正常。 所以,我的问题是,如何从套接字读取数据并用其内容更新ListView? 谢谢

很明显,它会阻塞UI线程

您的代码在pseudo中的外观:

Thread {
    //there is separate thread
    UiThread{
       //there is UI thread
       blockingOperation()
    }
}
换句话说,您当前的线程几乎是无用的,因为您在UI线程中执行阻塞操作

当然,它与

String reply = "test"
因为这不是阻塞操作

所以,要解决这个问题,就行动吧

String reply = bluetoothConnector.readSingleMessage();
内分螺纹:

String reply = bluetoothConnector.readSingleMessage();
Thread test = new Thread() {
    public void run() {
            try {
                final String reply = bluetoothConnector.readSingleMessage();
                currentAct.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listItems.add("other:" + String.valueOf(times));
                        listItems.add("other:" + reply);
                        itemsAdapter.notifyDataSetChanged();
                    }
                });
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
};