gpt4 book ai didi

Java线程代码问题

转载 作者:行者123 更新时间:2023-12-02 07:40:12 24 4
gpt4 key购买 nike

我有一个Java代码,它调用一个类的两个方法。就像下面这样,

import java.io.*;
class Example
{
public static void main(String args[])
{
try{
FileOutputStream fos = new FileOutputStream("1.dat");
DataOutputStream dos = new DataOutputStream(fos);

for(int i =0 ; i < 100 ; i++){
dos.writeInt(i);
}
dos.close();

FileOutputStream fos1 = new FileOutputStream("2.dat");
DataOutputStream dos1 = new DataOutputStream(fos1);

for(int i =100 ; i < 200 ; i++){
dos1.writeInt(i);
}
dos1.close();


Exampless ex = new Exampless();
ex.createArray(0);
ex.ReadData("1.dat");
ex.ReadData("2.dat");

}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}

class Exampless{

public static int []arr = new int [100] ;
void createArray(int z){
for(int i =z ; i < z+100 ; i++)
arr[i-z] = i ;
}
public synchronized void ReadData(String name){
try{
int cnt = 0;
FileInputStream fin = new FileInputStream(name);
DataInputStream din = new DataInputStream(fin);
for(int i = 0 ; i < 100 ; i++){
int c = din.readInt();
if(c == arr[i])
cnt++ ;
}

System.out.println("File name: " + name + " No. of Matches: " + cnt) ;
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}

在第一种方法中,代码将创建一个共享数组,在第二种方法中,代码会将其与文件进行比较。

现在,我想使用多个线程以并行方式运行这两个 ReadData() 方法。谁能帮我做到这一点。可能需要修改一些代码。

最佳答案

import java.io.*;
public class Example{
public static void main(String args[]) {
try {
FileOutputStream fos = new FileOutputStream("1.dat");
DataOutputStream dos = new DataOutputStream(fos);

for (int i = 0; i < 100; i++) {
dos.writeInt(i);
}
dos.close();

FileOutputStream fos1 = new FileOutputStream("2.dat");
DataOutputStream dos1 = new DataOutputStream(fos1);

for (int i = 100; i < 200; i++) {
dos1.writeInt(i);
}
dos1.close();

Exampless.createArray(0); //static method call to set the static arr variable
Exampless ex1 = new Exampless("1.dat");
Exampless ex2 = new Exampless("2.dat");
Thread t1 = new Thread(ex1);
Thread t2 = new Thread(ex2);
t1.start(); //calls the run method in ex1 in a new thread
t2.start();

} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}

class Exampless implements Runnable {

public static int[] arr = new int[100];
public String _name;

public Exampless(String name) {
this._name = name;
}

static void createArray(int z) {
for (int i = z; i < z + 100; i++) {
arr[i - z] = i;
}
}

@Override
public void run() {
try {
int cnt = 0;
FileInputStream fin = new FileInputStream(_name);
DataInputStream din = new DataInputStream(fin);
for (int i = 0; i < 100; i++) {
int c = din.readInt();
if (c == arr[i]) {
cnt++;
}
}
System.out.println("File name: " + _name + " No. of Matches: " + cnt);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}

}

关于Java线程代码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11711672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com