Q:?jiǎn)?dòng)三個(gè)線(xiàn)程停巷,同時(shí)讀取一個(gè)文件里胖眷,并記錄文件里"u51" 這個(gè)字符出現(xiàn)的次數(shù)。
A:涉及到多線(xiàn)程奉呛,可以用Callable接口來(lái)創(chuàng)建線(xiàn)程對(duì)象计螺,Callable接口是在java.util.concurrent包下面的夯尽。
import java.util.*;
import java.io.*;
import java.util.concurrent.*;
public class 多線(xiàn)程計(jì)數(shù)
{
public static void main(String[] args) throws Exception
{
File file=new File("a.txt");
Scanner sc=new Scanner(file);
ThirdThread tt=new ThirdThread();
tt.sc=sc;
FutureTask<Integer> task=new FutureTask<>(tt);
new Thread(task).start();
new Thread(task).start();
new Thread(task).start();
System.out.println(task.get());
}
}
class ThirdThread implements Callable<Integer>
{
public Scanner sc;
public int count;
@Override
public Integer call() throws Exception
{
while (sc.hasNextLine())
{
String str=sc.nextLine();
if (str.contains("u51"))
{
count++;
}
}
return count;
}
}