作者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://webptt.com/cn.aspx?n=bbs/java/M.1525838538.A.FC9.html
1F:→ ssccg: 多条thread本来就不会照顺序执行,你要依序执行为什麽不用05/09 13:01
2F:→ ssccg: single thread就好?05/09 13:02
3F:→ ssccg: 把new Thread移到最外面,整段都在一个thread里做才对吧05/09 13:03
嗯嗯,全部包在一个thread里可以跑喔,谢谢!
一开始的想法是想要拆成多个thread去执行,避免会有过多工作挤在一个thread里面的状
况,才想说是不是可以拆成多个thread去执行
※ 编辑: Dong0129 (114.137.132.57), 05/09/2018 13:28:31
4F:→ pass78: 可以多执行绪照顺序,用reactor 2的work queue event bus 05/20 22:46