目前我有这个素数发生器,限制在n <2 ^ 32-1.鉴于数组中元素的限制,我不完全确定如何进一步扩展限制.
筛:
public class Main {
public static void main(String args[]){
long N = 2000000000;
// initially assume all integers are prime
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to …Run Code Online (Sandbox Code Playgroud) 假设我想加载一个图像,"img.gif",从.JAR加载它或从硬盘加载它会更好吗?哪个更有效(速度和内存使用),还是它们基本相同?我知道从类路径加载可能更方便,但我无视这一点.
假设我有 5 个线程,它们必须1,000,000对并行蒙特卡罗方法程序进行总计函数调用。我1,000,000 / 5为 5 个线程中的每一个分配了函数调用。然而,经过多次测试(一些测试的迭代次数高达 1 万亿次),我意识到某些线程的完成速度比其他线程快得多。因此,我想动态地将工作负载分配给每个线程。我的第一个方法涉及一个AtomicLong初始值设置为 10 亿的变量。在每次函数调用之后,我会将 减AtomicLong1。在每次函数调用之前,程序都会检查 是否AtomicLong大于0,如下所示:
AtomicLong remainingIterations = new AtomicLong(1000000000);
ExecutorService threadPool = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {//create 5 threads
threadPool.submit(new Runnable() {
public void run() {
while (remainingIterations.get() > 0) {//do a function call if necessary
remainingIterations.decrementAndGet();//decrement # of remaining calls needed
doOneFunctionCall();//perform a function call
}
}
});
}//more unrelated code is …Run Code Online (Sandbox Code Playgroud) 每当我为我的JButton设置一个图标时,它的大小总是不正确.如何调整图标大小以完全适合按钮?
final JButton btnSanic = new JButton();
Image img = icon.getImage();
Image newimg = img.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH);
icon = new ImageIcon(newimg);
btnSanic.setIcon(icon);
Run Code Online (Sandbox Code Playgroud) 我用 Java 为桌面小部件制作了一个小时钟(该小部件还包括许多其他功能)。我在任务管理器中检查了应用程序 RAM 使用情况,发现时钟使用了 700+ MB 的 RAM。我禁用了时钟,RAM 使用量下降到大约 60 MB。这是时钟代码:
final int timeRun = 0;
new Thread()
{
public void run()
{
while(timeRun == 0)
{
Calendar cal = new GregorianCalendar();
int hour = cal.get(Calendar.HOUR);
int min = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
int AM_PM = cal.get(Calendar.AM_PM);
String day_night = "";
if (AM_PM == 1){
day_night = "PM";
}else{
day_night = "AM";
}
String time = hour + ":" + min + ":" + sec + " " …Run Code Online (Sandbox Code Playgroud) 假设我有一个像这样的 for 循环(忽略糟糕的效率,这只是一个例子):
ArrayList<Integer> primes = new ArrayList<>();
for(int i = 0; i < 10000; i++){
if(isPrime(i)){
primes.add(i);
}
}
Run Code Online (Sandbox Code Playgroud)
我想以 10% 的间隔显示循环的进度,但我不知道如何在不影响性能的情况下做到这一点。到目前为止我能想到的只有这些:
ArrayList<Integer> primes = new ArrayList<>();
int n = 10000/10;
for(int i = 0; i < 10000; i++){
if(isPrime(i)){
primes.add(i);
}
if(i == n){
System.out.println(String.valueOf(i).charAt(0)+"0% Complete");
n+=10000/10;
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更有效的方法来做到这一点?