- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我编写这个程序是为了寻找一个新号码。问题是我的程序没有停止。我知道我必须对线程做一些事情,但我不知道。
Primes
类(主要):
public class Primes {
/**
* The queue holding candidates we want to check for primality.
*/
private BlockingQueue<Integer> candidateQueue;
/**
* The queue holding primes we want to print before inserting into the result set.
*/
private BlockingQueue<Integer> primesQueue;
/**
* The set holding the numbers that we have determined are prime.
*/
private Set<Integer> primeNumbers;
/**
* Create a new instance of the Primes checker program.
*/
public Primes() {
// TODO: If this the best type of BlockingQueue to use, and is this the best size?
// Feel free to change both.
candidateQueue = new LinkedBlockingQueue<Integer>();
// TODO: If this the best type of BlockingQueue to use, and is this the best size?
// Feel free to change both.
primesQueue = new LinkedBlockingQueue<Integer>();
// TODO: Is a HashSet the best option here, and are there any options that would
// help make it perform better? Feel free to change to a different type of Set or
// to add parameters to the constructor.
primeNumbers = new HashSet<Integer>();
}
/**
* Actually run the primes finder, looking for primes between smallest and biggest (inclusive).
*
* @param smallest the smallest number to check
* @param biggest the biggest number to check
*
* @return a {@link Set} containing the prime numbers we have found
*/
public Set<Integer> findPrimesInRange(int smallest, int biggest) {
// TODO: You should create the number generator and primes printer, as well
// as some number of primality checkers. You should create these all as
// threads that you can run to look for prime numbers. You should have at least
// two instances of {@link PrimalityChecker}, but could have more if this makes
// your program faster.
// TODO: This is just here to make the compiler happy, you should return something real...
NumberGenerator a = new NumberGenerator( smallest,biggest,candidateQueue);
new Thread(a).start();
PrimalityChecker p1 = new PrimalityChecker(candidateQueue,primesQueue);
new Thread(p1).start();
PrimalityChecker p2 = new PrimalityChecker(candidateQueue,primesQueue);
new Thread(p2).start();
PrimesPrinter pp = new PrimesPrinter(primesQueue,primeNumbers);
Thread t1= new Thread(pp);
t1.start();
// t1.interrupt();
return primeNumbers;
}
public static void main(String[] args) {
Primes p = new Primes();
// Remember, 1 is not prime! http://en.wikipedia.org/wiki/Prime_number
p.findPrimesInRange(2, 100);
}
}
NumberGenerator
类:
public class NumberGenerator implements Runnable {
/** The biggest number we plan to check */
private final int biggestNumberToCheck;
/** A queue where we will place the numbers that we generate, which need to be checked */
private final BlockingQueue<Integer> candidateQueue;
private final int smallestNumberStart;
// TODO: What other state do we need?
/**
* Create a new instance of the NumberGenerator class, which will hand out numbers
* that need to be checked.
*
* @param smallest the smallest number to check
* @param biggest the biggest number to check
* @param queue the queue that we will put numbers to check into
*/
public NumberGenerator(int smallest, int biggest, BlockingQueue<Integer> queue) {
biggestNumberToCheck = biggest;
candidateQueue = queue;
smallestNumberStart = smallest;
}
public void run(){
for(int i=smallestNumberStart; i<=biggestNumberToCheck; i++){
//int rand= ThreadLocalRandom.current().nextInt(smallestNumberStart, biggestNumberToCheck);
candidateQueue.add(i);
}
}
// TODO: You can decide how you want to turn this into something runnable as a thread.
// Please look at the code examples we've discussed in class and at the lecture slides,
// as well as at the Concurrency tutorial: http://docs.oracle.com/javase/tutorial/essential/concurrency/
}
PrimalityChecker
:
public class PrimalityChecker implements Runnable {
/** A queue that holds generated numbers that we have not yet checked */
private final BlockingQueue<Integer> candidateQueue;
/** A queue where we place numbers when we determine they are prime */
private final BlockingQueue<Integer> primesQueue;
// TODO: What other state do we need?
/**
* Create an instance of the PrimalityChecker class, which will check numbers to see if
* they are prime and then insert them into a result queue.
*
* @param candidates queue that holds the candidates to check
* @param primes queue that holds prime numbers we have found
*/
public PrimalityChecker(BlockingQueue<Integer> candidates, BlockingQueue<Integer> primes) {
candidateQueue = candidates;
primesQueue = primes;
}
public void run(){
Iterator<Integer> itr = candidateQueue.iterator();
while(itr.hasNext()){
Integer Queue = null;
try {
Queue = candidateQueue.take();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (isPrime(Queue))
{
primesQueue.add(Queue);
// try {
// System.out.println(primesQueue.take());
// } catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
//}
}
}
//catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
//}
//
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
// TODO: You can decide how you want to turn this into something runnable as a thread.
// Please look at the code examples we've discussed in class and at the lecture slides,
// as well as at the Concurrency tutorial: http://docs.oracle.com/javase/tutorial/essential/concurrency/
}
PrimePrinter
:
public class PrimesPrinter implements Runnable {
/** A queue that holds numbers we have determined to be prime but have not yet processed */
private final BlockingQueue<Integer> primesQueue;
/** A set that holds all the prime numbers we have found */
private final Set<Integer> primesSet;
// TODO: What other state do we need?
/**
* Create an instance of the PrimesPrinter class, which will print any numbers that
* come in on the primes queue and then place them in the primes set.
*
* @param primes queue that holds prime numbers we have found but not yet processed
* @param primesSet set that holds all the prime numbers we have found
*/
public PrimesPrinter(BlockingQueue<Integer> primes, Set<Integer> primesSet) {
primesQueue = primes;
this.primesSet = primesSet;
}
@Override
public void run() {
// Iterator<Integer> itr = primesQueue.iterator();
// while (!Thread.currentThread().isInterrupted()){
while(primesQueue.size()>=0){
Integer Queue;
try {
Queue=primesQueue.take();
//Queue = primesQueue.poll(100, TimeUnit.MILLISECONDS);
//if(Queue==null){
// break;
//}
System.out.println(Queue);
primesSet.add(Queue);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最佳答案
只要至少有一个非守护线程处于 Activity 状态,JVM 就不会终止。
所以基本上你有两个选择,一个是 mark your processing thread as daemon ,所以它不会阻止 Java 退出。另一种选择是您实现某种信号机制,以便主线程可以在其工作结束时发出信号让所有其他线程停止。
在这两种情况下,您都需要决定挂起的工作是否要阻止您的关闭。在您将处理嵌套在各种线程上的情况下,您可能希望在排队特殊的“关闭”元素时终止所有队列处理线程(保留 run()
方法)。
// this is how you start a runable with a daemon thread
Thread t1 = new Thread(r1);
t1.setDaemon(true);
t1.start();
这是一个允许停止的示例(不完整)可运行文件:
public class PrimesPrinter implements Runnable {
public static final Integer LAST = new Integer(0); // values doesnt matter
private final BlockingQueue<Integer> primesQueue;
private int lastCount = 0;
public void run() {
while (true) {
Integer i = primesQueue.take(); // blocks
if (i == LAST) {
lastCount++; // wait for 2 checkers
if (lastCount == 2)
return;
else
continue; // next might be last or other result
}
System.out.println(i);
}
}
}
和
public class PrimalityChecker implements Runnable {
public static final Integer LAST = new Integer(42);
public void run() {
while (true) {
Integer i = candidateQueue.take();
if (i == PrimalityChecker.LAST) break;
if (isPrime(Queue))
primesQueue.add(Queue);
}
primesQueue.add(PrimesPrinter.LAST);
}
}
这就是您如何让初始线程将足够多的 LAST 元素加入队列,以便 worker 终止:
public NumberGenerator(int smallest, int biggest, BlockingQueue<Integer> queue) {
public void run(){
for(int i=smallestNumberStart; i<=biggestNumberToCheck; i++){
candidateQueue.add(i);
}
candidateQueue.add(PrimalityChecker.LAST);
candidateQueue.add(PrimalityChecker.LAST);
}
}
这当然需要生产者线程 NumberGenerator
将最后一个元素添加到候选队列,候选队列将最后一个元素添加到 primesQueue 等等。
关于java - 我的程序不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29908472/
我正在编写一个具有以下签名的 Java 方法。 void Logger(Method method, Object[] args); 如果一个方法(例如 ABC() )调用此方法 Logger,它应该
我是 Java 新手。 我的问题是我的 Java 程序找不到我试图用作的图像文件一个 JButton。 (目前这段代码什么也没做,因为我只是得到了想要的外观第一的)。这是我的主课 代码: packag
好的,今天我在接受采访,我已经编写 Java 代码多年了。采访中说“Java 垃圾收集是一个棘手的问题,我有几个 friend 一直在努力弄清楚。你在这方面做得怎么样?”。她是想骗我吗?还是我的一生都
我的 friend 给了我一个谜语让我解开。它是这样的: There are 100 people. Each one of them, in his turn, does the following
如果我将使用 Java 5 代码的应用程序编译成字节码,生成的 .class 文件是否能够在 Java 1.4 下运行? 如果后者可以工作并且我正在尝试在我的 Java 1.4 应用程序中使用 Jav
有关于why Java doesn't support unsigned types的问题以及一些关于处理无符号类型的问题。我做了一些搜索,似乎 Scala 也不支持无符号数据类型。限制是Java和S
我只是想知道在一个 java 版本中生成的字节码是否可以在其他 java 版本上运行 最佳答案 通常,字节码无需修改即可在 较新 版本的 Java 上运行。它不会在旧版本上运行,除非您使用特殊参数 (
我有一个关于在命令提示符下执行 java 程序的基本问题。 在某些机器上我们需要指定 -cp 。 (类路径)同时执行java程序 (test为java文件名与.class文件存在于同一目录下) jav
我已经阅读 StackOverflow 有一段时间了,现在我才鼓起勇气提出问题。我今年 20 岁,目前在我的家乡(罗马尼亚克卢日-纳波卡)就读 IT 大学。足以介绍:D。 基本上,我有一家提供簿记应用
我有 public JSONObject parseXML(String xml) { JSONObject jsonObject = XML.toJSONObject(xml); r
我已经在 Java 中实现了带有动态类型的简单解释语言。不幸的是我遇到了以下问题。测试时如下代码: def main() { def ks = Map[[1, 2]].keySet()
一直提示输入 1 到 10 的数字 - 结果应将 st、rd、th 和 nd 添加到数字中。编写一个程序,提示用户输入 1 到 10 之间的任意整数,然后以序数形式显示该整数并附加后缀。 public
我有这个 DownloadFile.java 并按预期下载该文件: import java.io.*; import java.net.URL; public class DownloadFile {
我想在 GUI 上添加延迟。我放置了 2 个 for 循环,然后重新绘制了一个标签,但这 2 个 for 循环一个接一个地执行,并且标签被重新绘制到最后一个。 我能做什么? for(int i=0;
我正在对对象 Student 的列表项进行一些测试,但是我更喜欢在 java 类对象中创建硬编码列表,然后从那里提取数据,而不是连接到数据库并在结果集中选择记录。然而,自从我这样做以来已经很长时间了,
我知道对象创建分为三个部分: 声明 实例化 初始化 classA{} classB extends classA{} classA obj = new classB(1,1); 实例化 它必须使用
我有兴趣使用 GPRS 构建车辆跟踪系统。但是,我有一些问题要问以前做过此操作的人: GPRS 是最好的技术吗?人们意识到任何问题吗? 我计划使用 Java/Java EE - 有更好的技术吗? 如果
我可以通过递归方法反转数组,例如:数组={1,2,3,4,5} 数组结果={5,4,3,2,1}但我的结果是相同的数组,我不知道为什么,请帮助我。 public class Recursion { p
有这样的标准方式吗? 包括 Java源代码-测试代码- Ant 或 Maven联合单元持续集成(可能是巡航控制)ClearCase 版本控制工具部署到应用服务器 最后我希望有一个自动构建和集成环境。
我什至不知道这是否可能,我非常怀疑它是否可能,但如果可以,您能告诉我怎么做吗?我只是想知道如何从打印机打印一些文本。 有什么想法吗? 最佳答案 这里有更简单的事情。 import javax.swin
我是一名优秀的程序员,十分优秀!