简体   繁体   English

在Java中使用in run方法调用方法进行多线程

[英]Calling a method with in run method for multi threading in java

I am trying to consume data from a blocked queue .The consume method needs to be implemented in the run method. 我正在尝试从阻塞的队列中使用数据。消耗方法需要在运行方法中实现。 I have following code which needs to implemented in run method 我有以下代码需要在run方法中实现

 @Override
public String consume(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException {
        long nextSourceOffset = 0;
        if (lastSourceOffset != null) {
            nextSourceOffset = Long.parseLong(lastSourceOffset);
        }
        if (queue.size() != 0) {
                Record record = getContext().createRecord("some-id::" + nextSourceOffset);
                Map<String, Field> map = new HashMap<>();
                try {
                    map.put("fieldName", Field.create(queue.take()));
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                record.set(Field.create(map));
                batchMaker.addRecord(record);
                ++nextSourceOffset;

            }


        return String.valueOf(nextSourceOffset);
    }

I am trying to make the above method to run in below "Run method" 我试图使上述方法在“运行方法”下运行

@Override
    public void run() {

        // TODO Auto-generated method stub

    }

Is there any way i can call it. 有什么办法可以打电话给我吗?

You can just make a class constructor that takes in the parameters like so: 您可以使类构造器接受如下参数:

public class ConsumeRunner implements Runnable{

        String lastSourceOffset;
        int maxBatchSize;
        BatchMaker batchMaker;
        public ConsumeRunner(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker)
        {
            this.lastSourceOffset=lastSourceOffset;
            this.maxBatchSize=maxBatchSize;
            this.batchMaker=batchMaker;
        }

        @Override
        public void run() {
            consume(lastSourceOffset,  maxBatchSize, batchMaker);

        }
    }

You construct your thread normally, except instead of the no-args constructor, you use the new custom one. 您可以正常构造线程,除了使用no-args构造函数之外,您可以使用新的自定义变量。 Otherwise running it is the same. 否则运行是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM