[問題] Thread執行時的問題

作者: Dong0129 (阿東跟上面講的情況一樣b)   2018-05-09 12:02:15
各位版友好,
我利用thread處理文件內容,
但是執行後發現不會依照行數順序執行..
try
{
FileReader reader=new FileReader("test.txt");
BufferedReader br=new BufferedReader(reader);
String line;
while((line=br.readLine())!=null)
{
final String fline=line;
new Thread()
{
@Override
public void run()
{
String head=command_class(fline,0).toUpperCase();
//command_class會得到每行第一個元素
if(head.equals("TITLE"))
{
runOnUiThread(new Runnable() {
public void run() {
textview.setText(line);
}
});
}
else if(head.equals("WRITE"))
{
String str=command_class(fline,1);
//command_class會得到每行第二個元素
runOnUiThread(new Runnable() {
public void run() {
textview.setText(line);
}
});
}
else if(head.equals("SLEEP"))
{
//sleep.start();
try
{
Log.i(TAG,"Sleep");
Thread.currentThread().sleep(100000);
}catch(Exception e)
{
e.printStackTrace();
}
}
else if(head.equals("READ"))
{
runOnUiThread(new Runnable() {
public void run() {
textview.setText(line);
}
});
}
}
}.start();
}
}catch(Exception e)
{
e.printStackTrace();
}
執行後發現還沒睡完就寫了下一行..
請問為什麼會這樣呢?
該怎麼調整才會按照順序執行呢?
作者: ssccg (23)   2018-05-09 13:01:00
多條thread本來就不會照順序執行,你要依序執行為什麼不用single thread就好?把new Thread移到最外面,整段都在一個thread裡做才對吧
作者: pass78   2018-05-20 22:46:00
可以多執行緒照順序,用reactor 2的work queue event bus

Links booklink

Contact Us: admin [ a t ] ucptt.com