如何在Java中使用多執行緒查詢質數和迴文數?


多執行緒是Java程式語言的一個特性,允許我們同時執行多個操作。在多執行緒中,操作被分成多個較小的部分,稱為執行緒。每個執行緒執行一個獨立的任務,而不會影響其他執行緒的效能。多執行緒的主要優點是能夠最佳化利用資源,例如CPU,並提高分配操作的執行速度。

查詢質數和迴文數是每個初級程式設計師都會執行的兩個基本程式設計任務。但是,在這篇文章中,我們將以一種令人興奮的方式來完成同樣的任務。我們將討論一個Java程式,該程式使用多執行緒環境(即使用執行緒)來查詢質數和迴文數。在這裡,執行緒是指大型操作的較小的子程序。

使用多執行緒查詢質數和迴文數的程式

我們將遵循以下方法,使用Java中的多執行緒查詢質數和迴文數。

方法

  • 建立一個名為“Thrd”的類,並在其中定義兩個名為“operation1()”和“operation2()”的靜態方法以及相應的引數。

  • 在“operation1()”中定義迴文數的邏輯,在“operation2()”中定義質數的邏輯。質數是一個只有兩個因數1和它本身的整數,而回文數正讀反讀都相同。

  • 接下來,建立兩個執行緒類。在第一個執行緒類中,透過傳遞引數來呼叫“operation1()”方法。類似地,在第二個執行緒類中呼叫“operation2()”方法。

  • 最後,在主方法中建立兩個執行緒類的物件,並使用內建方法“start()”執行它們。

示例

class Thrd {   
   // method to find palindrome number
   public static void operation1(int num) {    
      int num1 = num;
      int rev = 0;
      while(num1 != 0) {
         int rem = num1 % 10;
         num1 /= 10;
         rev = rev * 10 + rem;
      }
      if(num == rev) {
         System.out.println(num + " is a Palindrome number");
      } else {
         System.out.println(num + " is Not a Palindrome number");
      }  
   }
   // method to find prime number
   public static void operation2(int nums) {
      int countr = 0;
      if(nums == 2) {
         System.out.println(nums + " is a prime number");
      } else {
         for(int i = 1; i <= nums; i++) {
            if(nums % i == 0) {
               countr++;
            }
         }
         if(countr == 2) {
            System.out.println(nums + " is a prime number");
         } else {
            System.out.println(nums + " is not a prime number");
         }
      }
   }
}    
class Thrd1 extends Thread {   // thread number 1 
   public void run() {    
      Thrd.operation1(212); // calling method to check palindrome number   
   }    
}    
class Thrd2 extends Thread { // thread number 2    
   public void run() {    
      Thrd.operation2(23); // calling the method to check prime number   
   }    
} 
public class ThrdExecution {    
   public static void main(String args[]) {    
      // creating object for thread class
      Thrd1 oprt1 = new Thrd1();    
      Thrd2 oprt2 = new Thrd2();  
      // Starting the thread operation
      oprt1.start();    
      oprt2.start();  
   }    
}

輸出

23 is a prime number
212 is a Palindrome number

結論

我們從介紹多執行緒和執行緒開始這篇文章。然後,我們定義了問題陳述和我們的目標,即使用多執行緒查詢質數和迴文數。在下一節中,我們藉助示例程式討論了給定問題的解決方案。在我們的解決方案中,我們建立了兩個單獨的執行緒來獨立處理查詢質數和迴文數的操作。

更新於:2023年7月20日

490 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.