Java中的多线程 [英] multithreading in java

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

问题描述

我希望可运行"的运行速度为5tps.这不是并行执行的.

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

}

推荐答案

更新:霍华德是对的,我的第一个示例是错误的.

Update: Howard is right, my first example was wrong.

我已验证,如果您更改active()方法,此方法将有效:

I verified this works if you change your active() method:

service = Executors.newScheduledThreadPool(50);
new Thread() {
    public void run() {
        long nextTime = System.currentTimeMillis();
        while (true) {
            service.submit(runnable);
            long waitTime = nextTime - System.currentTimeMillis();
            Thread.sleep(Math.max(0, waitTime));
            nextTime += 200;
        }
    }
}.start();

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

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