在Java中以循环方式运行线程 [英] Running threads in round robin fashion in java

查看:731
本文介绍了在Java中以循环方式运行线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java中的多线程和同步的新手.我正在尝试实现一项任务,其中给了我5个文件,每个文件将由一个特定的线程读取.每个线程应从文件读取一行,然后将执行转发到下一个线程,依此类推.当所有5个线程都读取第一行时,然后再次从线程1运行行号开始.文件1中的2,依此类推.

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();

和ReadFile(在run方法中实现Runnable的情况下,我正在尝试在bufferreader对象上进行同步.

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 
}}

需要帮助

推荐答案

您错过了难题的许多部分:

You are missing many parts of the puzzle:

  • 您尝试在每个线程本地的对象上进行同步.这可能没有任何效果,并且JVM甚至可能删除了整个锁定操作;

  • 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;

您执行notifyAll而没有匹配的wait;

you execute notifyAll without a matching wait;

缺少的wait必须位于run方法的顶部,而不是您所指示的底部.

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

总的来说,恐怕现在修正您的代码超出了一个StackOverflow答案的范围.我的建议是首先使自己熟悉以下核心概念:Java中的锁的语义,锁如何与waitnotify互操作以及这些方法的精确语义.关于该主题的Oracle教程将是一个不错的开始.

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.

这篇关于在Java中以循环方式运行线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆