用java编写程序,java输入三个整数若干个整数,统计其中互不相同的整数的个数

java编程练习题_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
java编程练习题
&&java编程练习题
你可能喜欢藤本植物导航
&>&&>&&>&正文
编写一个Java应用程序,使用一个访问数组元素下标超界的语句,人为抛出...package com.kk.language_faculty. public class TestThrowsException1 { public static void main(String[] args) { TestThrowsException1 te = new TestThrowsException1(); te.check(new int[] { 1, 2, -3, 4, 5, 6, 10, -1, }); }...
编写一个Java应用程序,从键盘输入若干个正整数,如果输入为负数,抛掷自定义的异常
*/public class TestThrowsException2 { public void check(String str) {
char temp = ' ';/&#47: arr) {
if (i &////
中由字符 & + temp + & 导致异常!& + e./*
* 创建一个类Example,有一个String 型参数的方法---check() ,该方法用来检查参数中是否包含英文字母以外的字符。 * 如果包含,则抛出一个MyException异常;
te.check(new int[] { 1, 2;= 'z') || (temp & + i + & ---&);
} }}@SuppressWarnings(&serial&)class NegativeArraySizeException extends Exception { private int[] public NegativeArraySizeException(int[] array) {
this.array = } public int[] getArray() {
异常发生!;/&#47。 */@SuppressWarnings(&serial&)class MyException extends Exception { private S MyException(String content) {
this..//package com, 4, 5;
for (int i = 0; i & 0) {
throw new NegativeArraySizeException(arr);
} catch (NegativeArraySizeException ne) {
S/&#47.println(&发生了异常,继承自Exception类;--- &
} } public static void main(String[] args) {
TestThrowsException2 example = new TestThrowsException2();
example.check(&aa00bb11cc88dd//&#47.out.println(temp + & 是字母&);
throw new MyException(str);
} catch (MyException e) {
System.language_faculty.public class TestThrowsException1 { public static void main(String[] args) {
TestThrowsException1 te = new TestThrowsException1().println(&quot.out.getMessage()), -3.= 'a' && temp &lt.content = content!!字符串
&quotpackage com.// } public String getContent() {
///&#47, 正在处理中.。其中定义一个字符串成员content. * 生成一个构造方法对其赋值。并有一个成员方法取得其值;// i++) {
temp = str.charAt(i);
if ((temp &= 'Z')) {
S= 'A' && temp &lt,,gg--hh==jj((kk))zz&); }}/* * 创建一个异常类,将其命名为MyE/ee. + e.getContent()
+ &quot, 6, 10, -1, }); } public void check(int[] arr) {
for (int i ..& + ne.toString());
S str.length();// }}&#47.println(&quot.kk.language_faculty编写一个Java应用程序,从键盘输入若干个正整数,如果输入为负数,抛掷自定义的异常package com.kk.language_faculty.public class TestThrowsException1 { public static void main(String[] args) {
编写一个Java应用程序,使用一个访问数组元素下标超界的语句,人为抛出...package com.kk.language_faculty. public class TestThrowsException1 { public static void main(String[] args) { TestThrowsException1 te = new TestThrowsException1(); te.check(new int[] { 1, 2, -3, 4, 5, 6, 10, -1, }); }...java试编写一程序,可由键盘输入一个整数,然后判断该数值是正数还是负... 1、编写应用程序TestDemo.java,接收命令行的两个参数,要求不能输入负...import java.util.S public class TestJT { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("请输入整数"); int input= sc.nextInt(); if(input&=0){ System.out.println("你输入的是...JAVA:从键盘输入一个实数,求其平方根并输出。要求对输入为负数和非数字...Scanner sc = new Scanner(System.in); System.out.print("请输入x:"); String x = sc.nextLine().trim(); System.out.print("请输入y:"); String y = sc.nextLine().trim(); if (x.length() == 0 || y.length() == 0) { System.out.println("Ar...只导入Scanner这个包import java.io.BufferedR import java.io.InputStreamR public class test1{ public static void main(String arg[]){ System.out.println("请输入一个实数:"); String num=""; BufferedReader br=new BufferedReader(new InputStr...说明: 1)源程序中不得出现package关键字; 2)程序中的第一个大括号“{...哥们怎么又是你来?java!!!!怎么编程啊???由键盘输入非零整数x,判断出他的正负,正数输...public static void test(){ Scanner sc = new Scanner(System.in); long num = 0,negative = 0, positive = 0,sum = 0; List nums = new ArrayList(); do{ System.out.println("please enter a number :"); String s = sc.nextLine(); if (isNu...没有main 方法的原因 加个main方法应该就行了 public class Sum { public static void main(String[] args) { int j=0; for(i=1;iif (num&0) System.out.println("positive"); else System.out.println("negative"); if (num%2 == 0) System.out.println("even"); else System.out.println("odd");其他部分你自己写吧
我未做异常处理,参考一下
种植经验最新
种植经验推荐
& 6种植网 版权所有
渝ICP备号-23运行结果:
自己重写了一下推荐答案,加了些注释方便理解
import java.io.BufferedR
import java.io.F
import java.io.FileR
import java.io.FileW
import java.io.PrintW
import java.util.R
一个文件中有10000个数,用Java实现一个多线程程序将这个10000个数输出到5个不用文件中(不要求输出到每个文件中的数量相同)。
要求启动10个线程,两两一组,分为5组。
每组两个线程分别将文件中的奇数和偶数输出到该组对应的一个文件中,
需要偶数线程每打印10个偶数以后,就将奇数线程打印10个奇数,如此交替进行。
同时需要记录输出进度,每完成1000个数就在控制台中打印当前完成数量,并在所有线程结束后,在控制台打印”Done”.
* 分析:可以将10000个数分成5份,每一份(2000个数)对应一组,即两个线程,来分别输出这一份的奇数和偶数,
* 同时声明一个共享变量,用于统计当前所有线程输出的个数,反映记录的输出进度
public class PrintByThread {
public static void main(String[] args) {
//创建一个包含10000数字的输入文件
PrintWriter pw=new PrintWriter(new FileWriter(new File(&input.txt&)),true);
Random random=new Random();
for (int i = 0; i & 10000; i++) {
pw.print(Math.abs(random.nextInt())%100+&,&);
pw.flush();
pw.close();
//读取文件中的数字,分5次读取,每次读取2000个
BufferedReader reader=new BufferedReader(new FileReader(&input.txt&));
String str=reader.readLine();
reader.close();
String[] strs=str.split(&,&);//将一行字符串全部解析为10000个数字
int j=0;//10000个数的索引计数
for (int i = 0; i & 5; i++) {
int records[]=new int[2000];
for (int k = 0; k & 2000; k++) {
records[k]=Integer.parseInt(strs[j]);
//定义输出文件
PrintWriter writer =new PrintWriter(new FileWriter(new File(&output&+i+&.txt&)),true);
//定义实现的方法
ThreadGroup group=new ThreadGroup(records, writer);
//开启一对儿线程
new Thread(group).start();
new Thread(group).start();
} catch (Exception e) {
// TODO: handle exception
import java.io.PrintW
class ThreadGroup implements Runnable{
//所有类对象共享的同一个计数器count,记录总共输出的记录总数
private static int count=0;
//所有的ThreadGroup类对象共享一个锁,用于count变量的同步,任何一个线程需要修改count变量,必须取得该锁
private static Object lock=new Object();
public static final int EVEN=0;//代表偶数
public static final int ODD=1;//代表奇数
//*********以上静态变量,属于整个类所有***********
private int records[];
private PrintW//每组共享一个writer,输出到同一个文件
private int oddPoint=0;//记录每次打印奇数的起始位置
private int evenPoint=0;//记录每次打印偶数的起始位置
public ThreadGroup(int[] records,PrintWriter writer){
this.records=
this.writer=
this.type=EVEN;
//线程方法实现
public void run() {
while(print());
private synchronized boolean print(){
for(int i=0;i&10;){
//如果奇数和偶数都打印完成以后,就直接停止打印循环,等待该线程自己结束
if (oddPoint&=records.length&&evenPoint&=records.length) {
notifyAll();
//如果该线程该打印奇数,但奇数已经打印晚了,就直接停止本次10个数的打印,
//同理偶数,等下次切换打印类型后,再开始打印另外一种类型
if ((oddPoint&=records.length&&type==ODD)||(evenPoint&=records.length&&type==EVEN)) {
//判断开始打印偶数
if (type==EVEN) {
if (records[evenPoint]%2==0) {
writer.print(records[evenPoint]+&,&);
writer.flush();
//锁定全局变量方便线程输出后计数
synchronized (lock) {
if (count%1000==0) {
System.out.println(&当前完成数量:&+count);
if (count==10000) {
System.out.println(&Done!&);
//无论是否是偶数,打印成功一个后,偶数的起始位置都要后移
evenPoint++;
//打印奇数
if (records[oddPoint]%2==1) {
writer.print(records[oddPoint]+&,&);
writer.flush();
//锁定全局变量方便线程输出后计数
synchronized (lock) {
if (count%1000==0) {
System.out.println(&当前完成数量:&+count);
if (count==10000) {
System.out.println(&Done!&);
//无论是否是奇数,打印成功一个后,偶数的起始位置都要后移
oddPoint++;
type=~//切换打印类型
notifyAll();//一组中的任一线程打印完后唤醒另一个线程
wait();//释放锁进入等待状态,等待另一线程打印
} catch (Exception e) {
// TODO: handle exception
网易笔试估计过不去了。。。
import java.io.F
import java.io.PrintW
import java.net.URL;
import java.util.ArrayD
import java.util.Q
import java.util.S
public class Solve
public static void main(String[] args) throws Exception
URL url = CreateData.class.getResource(&/data.txt&);
Scanner scanner = new Scanner(new File(url.toURI()));
for (int i = 0; i & 10000; i++)
int data = Integer.parseInt(scanner.nextLine());
if (data % 2 == 0)
Common.ou.add(data);
Common.ji.add(data);
scanner.close();
Thread[] threads =new Thread[10];
for (int i = 0; i & 5; i++)
PrintWriter pw = new PrintWriter(new File(&./data&+i+&.txt&));
Common common=new Common();
threads[i*2] = new Thread(new WriterJi(pw,common));
threads[i*2+1] = new Thread(new WriterOu(pw,common));
for (Thread thread : threads)
thread.start();
class Common
//每组打印线程奇偶打印标志
public volatile boolean isJi =
private static int count = 0;
public static Queue&Integer& ji = new ArrayDeque&&(10000);
public static Queue&Integer& ou = new ArrayDeque&&(10000);
public static synchronized Integer jiGet()
if (!ji.isEmpty())
return ji.poll();
public static synchronized Integer ouGet()
if (!ou.isEmpty())
return ou.poll();
public static synchronized void inc()
if(++count %1000 ==0)
System.out.println(count);
if(count == 10000)
System.out.println(&Done&);
class WriterJi implements Runnable
public PrintW
private int count = 0;
public WriterJi(PrintWriter pw,Common common)
public void run()
while (!Common.ji.isEmpty() || !Common.ou.isEmpty())
if (common.isJi == true)
while (++count &= 10)
Integer data =Common.jiGet();
if(data != null)
pw.println(data);
pw.flush();
count = 0;
common.isJi =
class WriterOu implements Runnable
private PrintW
private int count = 0;
public WriterOu(PrintWriter pw,Common common)
public void run()
while (!Common.ji.isEmpty() || !Common.ou.isEmpty())
if (common.isJi == false)
while (++count &= 10)
Integer data =Common.ouGet();
if(data != null)
pw.println(data);
pw.flush();
count = 0;
common.isJi =
测试代码:
很多答案结果展示的不够完整,本人认为总共10000个数同步的分别放入多个文件是很重要的一点,这里是双线程,第一个跑了5037,第二个跑了4963.。。。我看很多代码符合题意,但不是等于题意,是题意所述情况的一个特殊情况。
package java_
import java.io.BufferedW
import java.io.F
import java.io.FileOutputS
import java.io.IOE
import java.io.OutputStreamW
publicclass Q22 {
public Integer sum = 10000;
public Object lock=new
= {true,true};
open(Q22 c,String addr,String addr2){
odd od1 = c.new odd();
even ev1 = c.new even();
od1.setsDestFile(addr);
ev1.setsDestFile(addr);
od1.setTag(&odd&+&
&+&tag1&);
ev1.setTag(&even&+&
&+&tag1&);
odd od2 = c.new odd();
even ev2 = c.new even();
od2.setsDestFile(addr2);
ev2.setsDestFile(addr2);
od2.setTag(&odd&+&
&+&tag2&);
ev2.setTag(&even&+&
&+&tag2&);
od1.id = 0;
od2.id = 1;
ev1.id = 0;
ev2.id = 1;
od1.start();
od2.start();
ev1.start();
ev2.start();
main(String[] args) throws IOException{
Q22 c = new Q22();
open(c,&./data/1.txt&,&./data/2.txt&);
publicstaticsynchronizedvoid
writeByFileOutputStream
(String _sDestFile,
String _sContent) throws IOException {
FileOutputStream fos = null;
File destFile = new File(_sDestFile);
BufferedWriter out = null;
out = new BufferedWriter(new
OutputStreamWriter(
new FileOutputStream(destFile, true)));
out.write(_sContent+&\r\n&);
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
} catch (IOException e) {
e.printStackTrace();
class odd extends Thread{
String sDestFile;
String tag;
public String getTag() {
setTag(String tag) {
this.tag =
public String getsDestFile() {
sDestFile;
setsDestFile(String sDestFile) {
this.sDestFile = sDestF
publicvoid
// TODO Auto-generated method stub
while(true){
synchronized(
if(sum&=0){
if(light[id]){
StringBuffer sb = new StringBuffer();
if(sum%1000 == 0){
System.out.println((10000-sum)
+ & has been done!&);
sb.append(sum--);
sb.append(tag);
writeByFileOutputStream(sDestFile,
sb.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(--this.num == 0
light[id] = false;
this.num = 10;
lock.notifyAll();
Thread.sleep(10);
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(!light[id]){
lock.notifyAll();
Thread.sleep(10);
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
class even extends Thread{
String sDestFile;
String tag;
public String getTag() {
setTag(String tag) {
this.tag =
public String getsDestFile() {
sDestFile;
setsDestFile(String sDestFile) {
this.sDestFile = sDestF
publicvoid
// TODO Auto-generated method stub
while(true){
synchronized(
if(sum&=0){
if(!light[id]){
StringBuffer sb = new StringBuffer();
if(sum%1000 == 0){
System.out.println((10000-sum)
+ & has been done!&);
sb.append(sum--);
sb.append(tag);
writeByFileOutputStream(sDestFile,
sb.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(--this.num == 0
light[id] = true;
this.num = 10;
lock.notifyAll();
Thread.sleep(10);
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(!light[id]){
lock.notifyAll();
Thread.sleep(10);
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
package com.sort.
import java.io.FileW
import java.io.IOE
import java.io.PrintW
import java.util.ArrayL
import java.util.L
public class ThreadFileDemo {
public static void main(String[] args){
String filename = &a.txt&;
String toFile = &b.txt&;
PrintWriter print =
FileWriter fw =
List&Integer& data = new ArrayList&Integer&();
产生随机数
for(int i = 0; i & 10000; i++){
data.add((int)(Math.random() * 1000));
fw = new FileWriter(filename);
fw.write(data.toString());
fw.close();
} catch (IOException e) {
e.printStackTrace();
print = new PrintWriter(new FileWriter(toFile));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String str = data.toString().substring(1, data.toString().length() - 1);
NumResource r = new NumResource(str.split(&, &), print);
ThreadOdd odd = new ThreadOdd(r);
ThreadEven even = new ThreadEven(r);
Thread t1 = new Thread(odd);
Thread t2 = new Thread(odd);
Thread t3 = new Thread(odd);
Thread t4 = new Thread(odd);
Thread t5 = new Thread(odd);
Thread t6 = new Thread(even);
Thread t7 = new Thread(even);
Thread t8 = new Thread(even);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
class NumResource{
public String[]
public boolean flag =
public PrintWriter print =
public NumResource(String[] str, PrintWriter print){
this.str =
this.print =
count = str.
// 奇数计数
public synchronized void odd(){
while(flag){
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
for(int i = 0; i & 10;){
if(s &= count){
if(print != null){
print.close();
System.out.println(&Done&);
System.exit(0);
如果奇数打印完毕,直接跳出
if(o &= count){
if(Integer.parseInt(str[o]) % 2 != 0){
System.out.println(&奇数:& + str[o] + &-& + s);
print.write(str[o] + &\n&);
print.flush();
printCount(o);
notifyAll();
// 偶数计数
public synchronized void even(){
while(!flag){
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
for(int i = 0; i & 10;){
结束关闭流,退出
if(s &= count){
if(print != null){
print.close();
System.out.println(&Done&);
System.exit(0);
如果偶数打印完毕,直接跳出
if(e &= count){
if(Integer.parseInt(str[e]) % 2 == 0){
System.out.println(&偶数:& + str[e] + &-& + s);
print.write(str[e] + &\n&);
print.flush();
printCount(e);
notifyAll();
public synchronized void printCount(int n){
if(s % 1000 == 0){
System.out.println(Thread.currentThread().getName() + &完成打印个数:&+ s);
class ThreadOdd implements Runnable{
private NumR
ThreadOdd(NumResource r){
public void run() {
while(true)
class ThreadEven implements Runnable{
private NumR
ThreadEven(NumResource r){
public void run() {
while(true)
package Chapter1;
import java.io.BufferedR
import java.io.F
import java.io.FileR
import java.io.FileW
import java.io.IOE
import java.io.PrintW
import java.util.concurrent.atomic.AtomicI
import java.util.concurrent.locks.ReentrantL
public class Main03
public static void main(String ...args) throws Exception
Main03 ob = new Main03();
ob.prepareTest();
BufferedReader br = new BufferedReader(new FileReader(&E:/input.txt&));
String str = br.readLine();
br.close();
String[] tokens = str.split(& &);
for(int i = 0;i & 5;i++)
int[] records = new int[2000];
PrintWriter pw = new PrintWriter(new FileWriter(&E:/output& + i + &.txt&));
for(int j = 0;j & 2000;j++)
records[j] = Integer.parseInt(tokens[i*2000 + j]);
ThreadGroup tg = new ThreadGroup(pw,records);
new Thread(tg).start();
new Thread(tg).start();
private void prepareTest()
File inputFile = new File(&E:/input.txt&);
FileWriter f =
PrintWriter pw =
f = new FileWriter(inputFile);
pw = new PrintWriter(f);
for(int i = 0;i & 10000;i++)
pw.write(i + & &);
pw.flush();
catch(IOException ioe)
ioe.printStackTrace();
if(f != null && pw != null)
f.close();
pw.close();
catch(Exception e)
e.printStackTrace();
class ThreadGroup implements Runnable
//10 threads shared
private static AtomicInteger totalNumbers = new AtomicInteger(0);
//2 threads in the same group shared
private PrintW
private ReentrantLock groupLock = new ReentrantLock();
private volatile int type = 0;
//0 for even thread,-1 for odd thread
private int oddPoint = 0;
private int evenPoint = 0;
private int[] toP
public ThreadGroup(PrintWriter writer,int[] numbers)
public void run()
while(doPrint());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
private boolean doPrint() throws InterruptedException
groupLock.lock();
//print 10 numbers
int recordsNum = toPrint.
for(int i = 0;i & 10;i++)
if(evenPoint &= recordsNum && oddPoint &= recordsNum)
if(evenPoint &= recordsNum && type == 0 || oddPoint &= recordsNum && type == 1)
//print even numbers
if(type == 0)
while(evenPoint & recordsNum && toPrint[evenPoint] %2 != 0)
evenPoint ++;
if(evenPoint &= recordsNum)
pw.write(toPrint[evenPoint] + &,&);
evenPoint++;
pw.flush();
int number = totalNumbers.incrementAndGet();
if(number % 1000 == 0)
System.out.println(&Processed & + number + & tokens!&);
while(oddPoint & recordsNum && toPrint[oddPoint] %2 == 0)
oddPoint ++;
if(oddPoint &= recordsNum)
pw.write(toPrint[oddPoint] + &,&);
oddPoint++;
pw.flush();
int number = totalNumbers.incrementAndGet();
if(number % 1000 == 0)
System.out.println(&Processed & + number + & tokens!&);
groupLock.unlock();
感觉这个题目好绕,我来个抛砖引玉吧~~
以上代码只做了简单的测试,不保证正确。
看到题目,首先想到的是把数据均分为5组,然后每组里面奇偶线程交替打印。要注意的是10个线程互斥访问总的计数器,并且每组里面的两个线程使用的是同一个流,所以要进行同步;简单写了一个,效率什么的肯定不行,主要是思路拿出来让大神们指点一下。
另外,其实题目并没有要求把数据平均地打印到5个输出文件中,所以感觉应该可以用forkjoin线程池来做,不过同一个组里面奇偶线程同步访问的问题是绕不开的,这个应该也是主要出错的地方。
import java.io.FileR
import java.io.FileW
import java.io.BufferedR
import java.io.PrintW
import java.util.A
import java.util.R
import java.util.concurrent.CountDownL
import java.util.concurrent.locks.C
import java.util.concurrent.locks.L
import java.util.concurrent.locks.ReentrantL
public class FileMultiThread {
private static final CountDownLatch door = new CountDownLatch(10); //同步工具类,可以确保n个线程的同步
public static void main(String[] args) {
FileMultiThread fmt = new FileMultiThread();
PrintWriter writer = new PrintWriter(new FileWriter(&F:\\number.txt&));
Random random = new Random();
for(int i = 0; i & 10000; i++){
writer.print(random.nextInt(10000)+&,&);
writer.flush();
writer.close();
BufferedReader reader = new BufferedReader(new FileReader(&F:\\number.txt&));
String numberString = reader.readLine();
reader.close();
String[] strArrays = numberString.split(&,&);
int step = 2000;
for(int i = 0; i & 5; i++){
int from = i *
int to = (i + 1) *
String[] records = Arrays.copyOfRange(strArrays, from,
//复制数组,有范围的复制,范围 from &= x & to
PrintWriter pw = new PrintWriter(new
FileWriter(&F:\\test&+ i + &.txt&));
PrintWriter pw1 = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(&F:\\summary.txt&),&GBK&)));
final outPutToFile opt = new outPutToFile(pw, records); //虽然五次循环下的CopyOfPrintTest1
//对象的名称相同,但因为五个对象的内容不同,所以这五个对象的引用是不同的,所以jvm在内存中
//会开辟五个独立的内存用来分别存储对象
fmt.odd(opt);
fmt.even(opt);
} //for结束
door.await(); //通过使用CountDownLatch来实现10个线程的同步。通过调用await()方法可以在所有线程结束之后打印&Done&
//每当主线程获取时间片,准备打印“Done”时,都会因为十个子线程尚未全部执行结束而被阻塞,直到十个子线程全部执行
//完毕(即死亡)而从改行恢复执行
System.out.println(&Done&);
} catch (Exception e) {
e.printStackTrace();
public void odd(final outPutToFile opt){
new Thread(new Runnable(){
public void run() {
while(opt.printOdd()){
door.countDown();
//每当线程结束,便调用CountDownLatch类的方法countDown()减1,当减到
//0时,即说明子线程全部执行结束,主线程可以执行下一步的代码
}).start();
public void even(final outPutToFile opt){
new Thread(new Runnable(){
public void run() {
while(opt.printEven()){
door.countDown();
}).start();
class outPutToFile{
private PrintWriter out =
private String[]
private static int count = 0; //静态变量(一个类只有一个),用来记录有效的输出次数
private boolean flag =
//全局变量,用来控制奇偶线程的执行,为true时,执行奇线程,为false时,执行偶线程
private Lock lock = new ReentrantLock(); //奇偶线程共享同一把锁
* 题目要求先打印10个奇数,再打印10个偶数,因此设置两个条件对象(更加灵活)。
* oddCondition下有三种情况:
1、当flag为false时,奇线程阻塞,偶线程执行;
2、当flag为true,且打印了10个奇数时,则偶线程唤醒,奇线程阻塞,偶线程执行;
3、当flag为true,但剩余奇数个数已不够时,则for循环结束,唤醒偶线程,继而当前线程结束
* evenCondition下有三种情况:
1、当flag为true时,偶线程阻塞,奇线程执行;
2、当flag为false,且打印了10个偶数时,则奇线程唤醒,偶线程阻塞,奇线程执行;
3、当flag为false,但剩余偶数个数已不够时,则for循环结束,唤醒奇线程,继而当前线程结束
private Condition oddCondition = lock.newCondition();
//条件对象之奇数对象
private Condition evenCondition = lock.newCondition(); //条件对象之偶数对象
* 问题:若数组中的2000个数,只有三个奇数,剩下的全是偶数,会发生什么情况?
* 思考:奇线程很快就会结束,只剩下偶线程。这时,如果偶线程在打印10个偶数后,将自己阻塞并尝试唤醒奇线程,
* 会发生什么?奇线程无法唤醒(已死亡),自己(偶线程)被阻塞,无法被唤醒,其任务永远无法继续下去,程序
* 设想:当奇/偶线程循环结束时,在另一个线程中使“阻塞自己,唤醒对方”的代码失效,一直循环执行,直到循环结束。
* 方案:记录奇/偶线程的循环次数。以奇线程为例,在奇线程中判断wholeEvenStep的值是否小于数组的长度,若小于,则说明对
* 方线程还没死亡,执行“阻塞自己,唤醒对方”的代码;否则,不执行,继续下一次循环。偶线程的操作同上。
private int wholeOddStep = 0; //用来记录奇线程执行的次数
private int wholeEvenStep = 0; //用来记录偶线程执行的次数
private static int array_length = 0;
//将数组的长度设置为静态变量
public outPutToFile(PrintWriter out,String[] records){
this.out =
this.records =
outPutToFile.array_length = records. //动态设置数组的长度
* 奇线程要执行的函数
public boolean printOdd(){
lock.lock(); //上锁,必须加上try/finally,以确保锁会被释放
int oddStep = 0; //记录奇线程有效的打印次数
boolean oddFlag = //设置函数返回值
* 之前用的是if(!flag){oddCondition.await();} else{...} ... 的形式,
* 这种用法的错误之处在于,当flag为false时,奇线程会进入阻塞状态;当其对应的偶线程将
* flag的值修改为true,并且唤醒奇线程时。奇线程便从阻塞的地方醒来,继续执行。结果就是
* 执行完if(...)中的代码后,并不会进入else中(虽然flag已为true),而是进行else
* 之后的代码。错误由此产生。
* 使用while(!flag){...}循环的好处在于,当奇线程从阻塞的地方醒来后,将继续循环执行,
* 如此,偶线程修改后的flag便会被检测出已为true,不符合当前条件,循环结束,进入之后真正
* 要执行的代码
while(!flag){
oddCondition.await();
for(int i = 0; i & array_ i++){
wholeOddStep =
int num = Integer.parseInt(records[i]);
if(num % 2 == 1){
//如果是奇数,则打印
out.print(num+&,&);
out.flush();
synchronized (outPutToFile.class) { //10个线程共用一个count,必须加锁保护,使其原子操作
if(count % 1000 == 0){ //每当打印1000个数时,则提示当前的数量
System.out.println(&当前完成数量:& + count);
oddStep++; //加1
if((wholeEvenStep + 1) & array_length){ //奇线程若未死亡,则执行以下代码,否则不执行
if(oddStep % 10 == 0){
//每打印10个奇数,则唤醒偶线程,并阻塞自己
evenCondition.signal();
oddCondition.await();
evenCondition.signal(); //循环正常结束后,唤醒偶线程
} catch (Exception e) {
e.printStackTrace();
lock.unlock();
oddFlag = //如果printOdd()执行结束,则说明调用这个方法的线程也即将结束
closeOut(wholeEvenStep,wholeOddStep);
return oddF
* 如果奇偶线程均执行完,则关闭输出流
* @param wholeEvenStep
* @param wholeOddStep
public void closeOut(int wholeEvenStep,int wholeOddStep){
if((wholeEvenStep == array_length) && (wholeOddStep == array_length)){
out.close();
* 偶线程调用的方法
public boolean printEven(){
lock.lock();
int evenStep = 0;
boolean evenFlag =
while(flag){
evenCondition.await();
for(int i = 0; i & array_ i++){
wholeEvenStep =
int num = Integer.parseInt(records[i]);
if(num % 2 == 0){
out.print(num+&,&);
out.flush();
synchronized (outPutToFile.class) {
if(count % 1000 == 0){
System.out.println(&当前完成数量:& + count);
evenStep++;
if((wholeOddStep + 1) & array_length){
if(evenStep % 10 == 0){
oddCondition.signal();
evenCondition.await();
oddCondition.signal();
} catch (Exception e) {
e.printStackTrace();
lock.unlock();
evenFlag = //如果printEven()执行结束,则说明调用这个方法的线程也即将结束
closeOut(wholeEvenStep,wholeOddStep);
return evenF
import java.io.F
import java.io.FileNotFoundE
import java.io.FileR
import java.io.FileW
import java.io.IOE
import java.io.PushbackR
import java.nio.CharB
import java.util.ArrayL
import java.util.A
import java.util.I
import java.util.L
import java.util.concurrent.CopyOnWriteArrayL
public class FileTest {
public static void main(String[] args) {
File file=new
File(&D:&+File.separator+&text.txt&);
if(file.length()&Integer.MAX_VALUE){
System.out.println(&文件内容长度过大!&);
char[] charBuffer=new char[(int) file.length()];
FileReader fileR
fileReader = new FileReader(file);
fileReader.read(charBuffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
List&Integer& list=getNumber(charBuffer);
for(int i=0;i&5;i++){
File fileIn=new
File(&D:&+File.separator+&in&+(i+1)+&.txt&);
if(!fileIn.exists()){
fileIn.createNewFile();
(IOException e) {
e.printStackTrace();
FileWriter fileWriter=new
FileWriter(fileIn,true);
PrintNum p=new PrintNum(list, fileWriter);
Runnable even=new evenThread(p);
Runnable odd=new oddThread(p);
Thread t1=new Thread(even);
Thread t2=new Thread(odd); t1.start();
t2.start();
} catch (IOException e) {
e.printStackTrace();
Thread.sleep(2000);
(InterruptedException e) {
e.printStackTrace();
System.out.println(&Done!&);
public static List&Integer& getNumber(char[] list){
List&Integer& result=new
ArrayList&Integer&();
Character a=
String a1=&&;
for(int i=0;i&list.i++){
if(list[i]!=' '){
if(list[i]=='-'){
a1=a1+(list[i]-'0');
if(a1!=&&){
result.add(Integer.valueOf(a1));
if(a1!=&&){
result.add(Integer.valueOf(a1));
class PrintNum{
private List&Integer&
private FileWriter fileW
private int printEven=0;
private int printOdd=10;
public PrintNum(List&Integer& list,FileWriter
fileWriter){
this.list=
this.fileWriter=fileW
public void printEven() throws IOException{
synchronized(fileWriter){
while(list.size()&0){
while(printEven&=10){
fileWriter.wait();
} catch (InterruptedException e) {
e.printStackTrace();
while(printEven&10){
printNumber(true);
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
printEven++;
printOdd=0;
fileWriter.notifyAll();
public void printOdd() throws IOException{
synchronized(fileWriter){
while(list.size()&0){
while(printOdd&=10){
fileWriter.wait();
} catch (InterruptedException e) {
e.printStackTrace();
while(printOdd&10){
printNumber(false);
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
printOdd++;
printEven=0;
fileWriter.notifyAll();
private void printNumber(boolean even) throws IOException{
boolean done=
synchronized (list) {
while(i&list.size() && !done){
if(even==true &&
Math.abs(list.get(i))%2==0){
String temp=list.get(i).toString()+&
fileWriter.write(temp,0,temp.length());
fileWriter.flush();
Iterator&Integer&
iter=list.iterator();
for(int k=0;k&=i;k++){
iter.next();
iter.remove();
else if(even==false &&
Math.abs(list.get(i))%2==1){
String temp=list.get(i).toString()+&
fileWriter.write(temp,0,temp.length());
fileWriter.flush();
Iterator&Integer&
iter=list.iterator();
for(int k=0;k&=i;k++){
iter.next();
iter.remove();
class evenThread implements Runnable {
private PrintN
public evenThread(PrintNum p){
public void run() {
try { p.printEven();
} catch (IOException e) {
e.printStackTrace();
class oddThread implements Runnable {
private PrintN
public oddThread(PrintNum p){ this.p=p;
public void run() {
p.printOdd();
} catch (IOException e) {
e.printStackTrace();
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题
浙ICP备号-2
扫一扫,把题目装进口袋

我要回帖

更多关于 java输入三个整数 的文章

 

随机推荐