⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 primes.java

📁 Java学习源代码检索系统免费版
💻 JAVA
字号:
//==============================================================
// Primes.java - Demonstrates Runnable interface
//
// Java学习源代码检索系统 Ver 1.0 20031015 免费正式版
// 版权所有: 中国IT认证实验室(www.ChinaITLab.com)
// 程序制作: ChinaITLab网校教研中心
// 主页地址: www.ChinaITLab.com    中国IT认证实验室
// 论坛地址: bbs.chinaitlab.com  
// 电子邮件: Java@ChinaITLab.com
//==============================================================

import java.io.IOException;

class Background implements Runnable {
 
 boolean finished = false;  // True to end run()
 int num = 3;               // Prime number candidates
 int delay;                 // Time between each output

 // Constructor
 Background(int delay) {
  this.delay = delay;
 }

 // Return true if num is a prime number
 public boolean isPrime(int n) {
  for (int i = 2; i < n; i++)
   if ((n % i) == 0)
    return false;
  return true;
 }

 // Search for prime numbers in the background
 public void run() {
  try {
   while (!finished) {
    if (isPrime(num))
     System.out.println(num);
    num++;
    Thread.sleep(delay);
   } // while
  } catch (InterruptedException e) {
   return;
  }
 }

 // Set flag to stop run()
 public void halt() {
  finished = true;
 }

}

// Compute prime numbers in the background
class Primes {

 static char getChar() {
  char ch = '\0';
  try {
   ch = (char)System.in.read();
  } catch (IOException e) {
   System.out.println(e.getMessage());
  }
  return ch;
 }

 static void waitForKey(char key) {
  while (getChar() != key) /* wait */ ;
 }

 public static void main(String args[]) throws Exception {
  System.out.println("Press Enter to begin and again to quit");
  waitForKey('\n');
  // Construct and start thread
  Background background = new Background(50);
  Thread T = new Thread(background);
  T.setPriority(4);
  T.start();
  // Wait for Enter key while thread runs
  waitForKey('\n');
  background.halt();  // Stop the thread
 }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -