java 多线程 保存txt_一个txt文件,里面存在几万条数据,现用多线程实现数据导入,提高效率,java代码如何实现...

先读取文件数据,每条数据开启一个线程,然后导入,demo

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;

/**

* 用多线程导入同一个文件中数据,不能重复导入。

* 目的:提高执行速度,缩短执行时间

* @author Administrator

*

*/

public class TestThreadNew  {

private  static long startTime;//开始时间

private static   long endTime;//结束时间

public static void readFile()  {

File  file=new File("c://test.txt");

try {

InputStreamReader isr=new InputStreamReader(new FileInputStream(file),"GBK");

BufferedReader br=new BufferedReader(isr);

startTime=System.currentTimeMillis();

TestThreadNew2 tt;

String str="";

int n=0;

try {

while((str=br.readLine())!=null){

tt=new TestThreadNew2();

n++;

tt.str2=new String(str.getBytes(),"UTF-8");

tt.n=n;

new Thread(tt).start();

try {Thread.sleep(60);} catch (InterruptedException e) {e.printStackTrace();}

}

System.out.println("耗时:"+(endTime-startTime));

} catch (IOException e) {

e.printStackTrace();

}

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

readFile();//获取文件daoru

}

public long getEndTime() {

return endTime;

}

public void setEndTime(long endTime) {

this.endTime = endTime;

}

}

public class TestThreadNew2  implements Runnable{

public   String str2;//当前行内容

public   int n=0;//当前条数

public   long endTime;//结束时间

TestThreadNew ttn;

@Override

public  void run() {

try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}

String[] array=str2.split(",");

System.out.println("当前用的线程:"+Thread.currentThread().getName()+"---第"+n+"条:---"+array[0]);

ttn=new TestThreadNew();

endTime=System.currentTimeMillis();

ttn.setEndTime(endTime);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值