java thread循环,在Java中以循环方式运行线程

I am new to Multithreading and synchronization in java. I am trying to achieve a task in which i am given 5 files, each file will be read by one particular thread. Every thread should read one line from file then forward execution to next thread and so on. When all 5 threads read the first line, then again start from thread 1 running line no. 2 of file 1 and so on.

Thread ReadThread1 = new Thread(new ReadFile(0));

Thread ReadThread2 = new Thread(new ReadFile(1));

Thread ReadThread3 = new Thread(new ReadFile(2));

Thread ReadThread4 = new Thread(new ReadFile(3));

Thread ReadThread5 = new Thread(new ReadFile(4));

// starting all the threads

ReadThread1.start();

ReadThread2.start();

ReadThread3.start();

ReadThread4.start();

ReadThread5.start();

and in ReadFile (which implements Runnable, in the run method, i am trying to synchronize on bufferreader object.

BufferedReader br = null;

String sCurrentLine;

String filename="Source/"+files[fileno];

br = new BufferedReader(new FileReader(filename));

synchronized(br)

{

while ((sCurrentLine = br.readLine()) != null) {

int f=fileno+1;

System.out.print("File No."+f);

System.out.println("-->"+sCurrentLine);

br.notifyAll();

// some thing needs to be dine here i guess

}}

Need Help

解决方案

You are missing many parts of the puzzle:

you attempt to synchronize on an object local to each thread. This can have no effect and the JVM may even remove the whole locking operation;

you execute notifyAll without a matching wait;

the missing wait must be at the top of the run method, not at the bottom as you indicate.

Altogether, I'm afraid that fixing your code at this point is beyond the scope of one StackOverflow answer. My suggestion is to first familiarize yourself with the core concepts: the semantics of locks in Java, how they interoperate with wait and notify, and the precise semantics of those methods. An Oracle tutorial on the subject would be a nice start.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值