Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

multithreading in java

I want "runnable" to run at 5tps. This is not executing paralelly.

package tt;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public class mySpawner {

public int tillDone = 0;
public int tillMax = 0;
public ArrayList arrayList;
private myWorker myworking;
private ScheduledExecutorService service = Executors.newScheduledThreadPool(50);

Runnable runnable = new Runnable() {

    @Override
    public void run() {
        try {
            System.out.println(System.nanoTime());
            Thread.sleep(7000);
        } catch (InterruptedException ex) {
            Logger.getLogger(mySpawner.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
};


public void activate() {
    try {
        service = Executors.newScheduledThreadPool(50);
        service.scheduleAtFixedRate(runnable, 0, 200, TimeUnit.MILLISECONDS);
    } catch (Exception e) {//Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

}

public void deactivate() {
    service.shutdown();
}

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Consider this:

  • Your tasks are sleeping for 7 seconds during their execution
  • You are scheduling a new task every 200ms
  • You only have 50 threads in your executor

It should be clear, I hope, that you'll run out of pooled threads in just a few seconds, and you'll lose your parallelism. You need to balance this better, either by reducing the rate or reducing the sleep. Increasing the pool size won't help, you'll still run out of threads.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...