我需要以定时间隔从4个单独的.csv
数据文件中提取数据,以同时输出数字。我只能按顺序提取文件。我不确定线程是否有用,而且我从来没能让它们正常运行。我的最终结果将在JFrame
中显示输出。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Inputtest {
public static void main(String[] args) throws IOException, InterruptedException {
O21 a = new O21();
O22 b = new O22();
PH1 c = new PH1();
PH2 d = new PH2();
a.O21();
b.O22();
c.PH1();
d.PH2();
}
}
class O21
{
public void O21() throws FileNotFoundException, InterruptedException {
int e = 21; //preset Level
Scanner O1 = new Scanner(new File("O21.txt"));
O1.useDelimiter(",");
while (O1.hasNext()) {
String a = O1.next();
int aa = Integer.parseInt(a);
Thread.sleep(500); // Time delay for output
if (a.trim().isEmpty()) { continue; }
if(aa > (e + 1)) {
System.out.println(a);
System.out.println("Alarm high");
continue;
}
if(aa < (e-1)) {
System.out.println(a);
System.out.println("Alarm Low");
continue;
}
System.out.println(a);
}
}
}
class O22 {
public void O22() throws FileNotFoundException, InterruptedException {
double f = 20; //preset Level
Scanner O2 = new Scanner(new File("O22.txt"));
O2.useDelimiter(",");
while (O2.hasNext()) {
String b = O2.next();
int bb = Integer.parseInt(b);
Thread.sleep(500); // Time delay for output
if (b.trim().isEmpty()) { continue; }
if(bb > (f + 1)) {
System.out.println(b);
System.out.println("Alarm high");
continue;
}
if (bb < (f - 1)) {
System.out.println(b);
System.out.println("Alarm Low");
continue;
}
System.out.println(b);
}
}
}
class PH1 {
public void PH1() throws FileNotFoundException, InterruptedException {
double g = 7; //preset Level
Scanner P1 = new Scanner(new File("PH1.txt"));
P1.useDelimiter(",");
while (P1.hasNext()) {
String c = P1.next();
double cc = Double.parseDouble(c);
Thread.sleep(1000); // Time delay for output
if (c.trim().isEmpty()) { continue; }
if (cc > (g + .5)) {
System.out.println(c);
System.out.println("Alarm high");
continue;
}
if (cc < (g - .5)) {
System.out.println(c);
System.out.println("Alarm Low");
continue;
}
System.out.println(c);
}
}
}
class PH2 {
public void PH2() throws FileNotFoundException, InterruptedException {
double h = 7; //preset Level
Scanner P2 = new Scanner(new File("PH2.txt"));
P2.useDelimiter(",");
while (P2.hasNext()) {
String d = P2.next();
double dd = Double.parseDouble(d);
Thread.sleep(1000); // Time delay for output
if (d.trim().isEmpty()) { continue; }
if (dd > (h + .5)) {
System.out.println(d);
System.out.println("Alarm high");
continue;
}
if (dd < (h - .5)) {
System.out.println(d);
System.out.println("Alarm Low");
continue;
}
System.out.println(d);
}
}
}
答案 0 :(得分:1)
是的,线程会帮助你。非常简单,
class O21 implements Runnable
{
@Override public void run() // Used to be your constructor
{
....
并使用main
方法:
...
Thread a = new Thread( new O21() );
a.start();
...
,同样适用于O22
,PH1
和PH2
,它们现在都会同时执行。
您可以向Runnable
添加构造函数,以便将refs传递给JFrame
。我会把它留作练习。此外,SO和其他地方的线程编程有很多资源。
干杯,