作者Dong0129 (阿東)
看板java
標題[問題] Thread執行時的問題
時間Wed May 9 12:02:15 2018
各位版友好,
我利用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();
}
執行後發現還沒睡完就寫了下一行..
請問為什麼會這樣呢?
該怎麼調整才會按照順序執行呢?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.137.132.57
※ 文章網址: https://www.ptt.cc/bbs/java/M.1525838538.A.FC9.html
→ ssccg: 多條thread本來就不會照順序執行,你要依序執行為什麼不用05/09 13:01
→ ssccg: single thread就好?05/09 13:02
→ ssccg: 把new Thread移到最外面,整段都在一個thread裡做才對吧05/09 13:03
嗯嗯,全部包在一個thread裡可以跑喔,謝謝!
一開始的想法是想要拆成多個thread去執行,避免會有過多工作擠在一個thread裡面的狀
況,才想說是不是可以拆成多個thread去執行
※ 編輯: Dong0129 (114.137.132.57), 05/09/2018 13:28:31
→ pass78: 可以多執行緒照順序,用reactor 2的work queue event bus 05/20 22:46