您的位置:程序门 -> java -> j2se / 基础类



多线程问题


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


多线程问题
发表于:2007-10-09 15:13:47 楼主
利用多线程  
如何可以做到以下事情  
如  
线程1:  
读文件内容(快1),操作快1事情,写文件内容(快1)  
线程2:  
读文件内容(快2),操作快2事情,写文件内容(快2)  
线程3:  
读文件内容(快3),操作快3事情,写文件内容(快3)  
保证读的内容,写文件内容不重复
发表于:2007-10-09 16:20:571楼 得分:0
import   java.io.*;
class   threaddemo{
public   static   void   main(string   args[]){
                    threads   t;
                    string   s;
                    for(int   i=1;i <=3;i++){
                        integer   index=new   integer(i);
                        s="test"   +   index.tostring()   +".txt";
                        t=new   threads(s);
                        t.start();
                    }
}
}
class   threads   extends   thread{
private   string   filename;
public   threads(string   name){
filename=name;
}
public   void   run(){
                    try{
                        bufferedreader   in   =   new   bufferedreader(new   inputstreamreader(new
                                fileinputstream(filename)));
                        string   line;
                        while   (   (line   =   in.readline())   !=   null)   {
                            system.out.println(line);
                        }
                    }
                    catch(exception   ex){
                        system.out.println("异常:   "   +ex);
                    }
}
}

花了些时间,读出来了,没有写回去了,我相信你能写回去了吧.
发表于:2007-10-19 11:26:142楼 得分:0
老大这个读取多个文件
我是说读取一个文件的内容的记录;
发表于:2007-10-19 11:35:443楼 得分:0
可以考虑把文件内容先读到缓冲里,然后三个线程分别处理不同的部分
最后等所有线程结束后,再把缓冲内容保存到硬盘上
发表于:2007-10-19 11:37:594楼 得分:0
byte[]   buf=..//读取到缓冲
thread   t1=new   thread(){
      public   void   run()
      {
            //读.写   块1
      }
}
t1.start();

thread   t2=new   thread(){
      public   void   run()
      {
            //读.写   块2
      }
}
t2.start();

thread   t3=new   thread(){
      public   void   run()
      {
            //读.写   块3
      }
}
t3.start();

t1.join();
t2.join();
t3.join();
//保存文件到磁盘
发表于:2007-10-19 11:43:385楼 得分:0
支持4楼的方法


快速检索

最新资讯
热门点击