1、采用public static的变量存储这一数值,每个线程都往这一共有静态变量里写入已复制大内小。 2、采用Callable方式实现多线程,容将结果作为返回值返回到主线程。这一方法只能在所有子线程都完成之后才能通过future获取。
Ⅱ C++多线程操作文件遇到的问题!
句柄和指针都可以有多个,读的时候可以同时读,但是写的时候要注意互斥,一次只能有一个进行写操作,并且写的时候不能读。这些可以使用mutex实现。
Ⅲ 求多线程读取一个文件,然后写到另外一个文件中的Java实现。
这个是我写的三个类,用于多线程操作读取文件内容和写入文件内容,不知道是不是你合你味口。
________________第一个类______读取内容__写入内容____________________
package pro;
import java.io.*;
public class ReadFileToWriteOtherFile {
private File oldFile;
private File newFile;
private BufferedReader br;
private BufferedWriter bw;
private String totalString="";
private Boolean flag=true; //用于标记文件名是否存在 true表示存在
public ReadFileToWriteOtherFile()
{
oldFile=null;
newFile=null;
br=null;
bw=null;
System.out.println("初始化成功");
}
public void readInfoFromFile(String fileName)
{
System.out.println("开始读取");
try
{
oldFile=new File(fileName);
if(oldFile.exists()) //如果文件存在
{
System.out.println("存在");
br=new BufferedReader(new FileReader(oldFile));
String info=br.readLine(); //读取一行
while(info!=null)
{
totalString+=info; //将读取到的一行添加到totalString中
info=br.readLine(); //再读取下一行
//System.out.println(totalString);
}
System.out.println("读取完成,准备写入…………");
}
else //如果文件不存在
{
System.out.println("文件不存在");
flag=false; //标记该文件不存在
}
// System.out.println("totalString="+totalString);
}
catch(FileNotFoundException e)
{
System.out.println(e);System.out.println("开始读取中1");
}
catch(IOException e)
{System.out.println(e);System.out.println("开始读取中2");}
}
public void writeInfoToFile(String fileName)
{
if(!flag) //如果标记前面的文件不存在,则return
{
flag=true; //改回原来的文件标记符
return;
}
try
{
newFile=new File(fileName);
if(newFile.exists()) //如果存在,不用创建新文件
{
System.out.println("文件存在,可以写入!");
}
else //如果不存在,则创建一个新文件
{
System.out.println("文件不存在,准备创建新文件");
newFile.createNewFile();
System.out.println("文件创建成功,可以写入");
}
bw=new BufferedWriter(new FileWriter(newFile,true));
// System.out.println("totalString="+totalString);
bw.write(totalString,0,totalString.length());
bw.flush(); //刷新缓冲区
System.out.println("写入完成");
totalString="\r\t"; //清空原来的字符串
}
catch(FileNotFoundException e)
{System.out.println(e);}
catch(IOException e)
{System.out.println(e);}
}
}
________________第二个类______一个自定义的线程类____________________
package pro;
import java.lang.Thread;
public class MyThread extends Thread
{
private int index; //用于数组的位置
private String[] fileNames; //定义一个字符串数组
ReadFileToWriteOtherFile bftwo=new ReadFileToWriteOtherFile(); //定义前面的自定义类
public MyThread(String[] fileNames,int index) //index表示数组位置标号
{
this.index=index;
this.fileNames=fileNames;
}
public void run()
{
bftwo.readInfoFromFile(fileNames[index]);//传入数组中的字符串参数
bftwo.writeInfoToFile("b.txt"); //传入写入的目的地文件
//index++; //数组位置加1
System.out.println("==============");//分隔线
}
}
________________第三个类______主程序____________________
package pro;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.support.;
import java.io.*;
public class BeanRunApp {
/**
* Method main
*
*
* @param args
*
*/
public static void main(String[] args)
{
/* ApplicationContext apc=new ("beans.xml");
ClassRoom croom=(ClassRoom)apc.getBean("classRoom");
croom.out();
System.out.println("over");
*/
long startTime=System.currentTimeMillis();
String[] a={"a.txt","c.txt","d.txt","e.txt"}; //用一个符品数组保存文件名
for(int i=0;i<a.length;i++) //用数组的长度来作为循环条件
{ //把这个数组和i的值作为构造函数传入线程类
MyThread myth=new MyThread(a,i);
System.out.println("--------------------------------");
myth.start(); //执行
System.out.println("当前的线程是:"+myth.getName());
}
long endTime=System.currentTimeMillis();
System.out.println("耗时:"+(endTime-startTime)+"毫秒");
}
}
Ⅳ writefile 多线程写多文件 该如何做
下面的程序,编译之后,你可以运行很多个实例,目前我将文件写在了D:\1.txt,每个程序写1000行数据,这些值你可以自己更改(比如 写在C:,每个程序写10000行等),等程序都写完后,你可以去文件中查看写文件的结果。补充一下,我是在VC6.0环境中写的,所以windows.h,如果你不是在这个环境中的话,可能需要修改一些定义,比如DWORD等。其他的API都是windows平台提供的API;
#include <stdio.h>
#include "windows.h"
int main()
{
//获取进程ID,因为你希望是多个进程运行同时写一个文件,所以,我们打印出进程ID
DWORD dwProcessID = GetCurrentProcessId();
//初始化我们要写入文件中的内容,及该内容长度;
char szContent[100] = {0};
sprintf(szContent,"process[%u] write file\r\n",dwProcessID);
DWORD dwContentLen = strlen(szContent);
//创建互斥量,这样可以进行进程间的互斥,当然用这个也可以做线程间的互斥
HANDLE hMutex = CreateMutex(NULL,FALSE,"MyFileMutex");
if (NULL == hMutex)
{
printf("[%u]Create/Open Mutex error!\r\n",dwProcessID);
return 1;
}
//创建或打开文件
HANDLE hFile = CreateFile("D:\\1.txt",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE | FILE_SHARE_READ,NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_ARCHIVE,
NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
printf("[%u]Creat/Open file error!\r\n",dwProcessID);
return 1;
}
//循环写入文件
for(int i = 0; i < 1000 ; i++)
{
//等待临界资源,即锁定文件
WaitForSingleObject(hMutex,INFINITE);
printf("Process[%u] Get the signal\r\n",dwProcessID);
DWORD len = 0;
//因为是共享写文件,即多个程序写一个文件,所以一定要将文件指针偏移到尾部
SetFilePointer(hFile,0,NULL,FILE_END);
//写入文件
BOOL rnt = WriteFile(hFile,szContent,dwContentLen,&len,NULL);
if (rnt == FALSE)
{
printf("Process[%u] Fail to write file\r\n",dwProcessID);
}
//释放互斥量,解除锁定
ReleaseMutex(hMutex);
//加个Sleep便于我们中间观察结果
Sleep(30);
}
CloseHandle(hMutex);
CloseHandle(hFile);
return 0;
}
应你要求,我把AIP中的宏定义解释如下:
HANDLE hFile = CreateFile("D:\\1.txt",
GENERIC_READ | GENERIC_WRITE,//表示程序对该文件有读和写的权限
FILE_SHARE_WRITE | FILE_SHARE_READ,//表示可以多个程序共享读和写的权限
NULL,
OPEN_ALWAYS,//表示打开该文件,如果该文件不存在,则创建该文件
FILE_ATTRIBUTE_ARCHIVE,//文件的属性为存档
NULL);
WaitForSingleObject(hMutex,INFINITE);
//INFINITE表示永远等待,直到hMutex有信号为止
SetFilePointer(hFile,0,NULL,FILE_END);
//FILE_END表示从文件尾部开始偏移;实际此举就是将文件指针偏移到文件尾部;
Ⅳ 怎么避免多线程同时读写文件
Java中不同的线程是可以同时操作一个文件的,只不过有时候因为进程执行的快慢,会出现数据读取不同步的问题,例子如下:Public class Readfile implements Runnable{ public void run(){ FileInputStream inputStream = new FileInputStream(file);//读数据 byte[] buffer = new byte[1024]; int size; while ((size = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, size);//写数据 } inputStream.close();// outputStream.close(); } public satatic void main(String args []) throws InterruptedException{ Readfile rf = new Readfile(); Thread t1 = new Thread(rf);//开启一个线程 Thread t2 = new Thread(rf);//开启第二个线程 t1.start(); t2.start(); }}
Ⅵ c语言文件读写 多线程
主线程读的是A文件,次线程写的是B文件,两者不冲突。4K的buffer已经算很小了。重点是主次线程共享的数据需要做同步,所以才造成了要等待的现象。你说的类似消费者和生产者模型。
Ⅶ java多线程读写文件
public static void main(String[] args) {
File data = new File("data.txt");
try {
InputStreamReader read = new InputStreamReader(new FileInputStream(
data), "UTF-8");
final BufferedReader bufferedReader = new BufferedReader(read);
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@
public void run() {
String lineTXT = null;
synchronized (bufferedReader) {
try {
while ((lineTXT = bufferedReader.readLine()) != null) {
System.out.println(Thread.currentThread()+":"+lineTXT);
bufferedReader.notify();
bufferedReader.wait();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
bufferedReader.notifyAll();
}
}
}
}).start();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Ⅷ qt 怎么使用多线程遍历文件夹
一、Qt遍历文件夹下一层的文件:
方式1:
void ImageTree::addFolderImages(QString path)
{
//判断路径是否存在
QDir dir(path);
if(!dir.exists())
{
return;
}
dir.setFilter(QDir::Files | QDir::NoSymLinks);
QFileInfoList list = dir.entryInfoList();
int file_count = list.count();
if(file_count <= 0)
{
return;
}
QStringList string_list;
for(int i=0; i
{
QFileInfo file_info = list.at(i);
QString suffix = file_info.suffix();
if(QString::compare(suffix, QString("png"), Qt::CaseInsensitive) == 0)
{
QString absolute_file_path = file_info.absoluteFilePath();
string_list.append(absolute_file_path);
}
}
}
分析:遍历文件的下一层,对于系统而言包括:文件夹、文件、快捷方式,使用setFilter即可过滤。通过entryInfoList则可以获取过滤后所得到的文件夹下的文件信息列表,遍历文件通过操作QFileInfo可得到所需的文件详细信息(大小、类型、后缀等)。