簡體   English   中英

Java線程創建

[英]Java Thread Creation

我正在嘗試使用可運行方法創建線程。下面的代碼

public class NewClass implements Runnable{
     public static void main(String[] agrg){
            NewClass n =new NewClass();
            n.start();
      }
      void start(){
            Thread th=new Thread();
            th.start();
      }
      @Override
      public void run() {
            System.out.println("Thread");
      }
}

在這種覆蓋方法中,我應該調用run,但是沒有發生

您的run()方法屬於NewClass ,它不是Thread,而是一個工作線程。

因此,沒有人會調用NewClass run()方法

在Java中,當通過實現Runnable創建工作run() ,應僅覆蓋run()方法。 並將此工作程序的實例傳遞給線程,例如

new Thread(new NewClass()).start();

因此,您可以執行以下操作

public class NewClass implements Runnable{
     public static void main(String[] agrg){
            NewClass n =new NewClass();
            n.start();
      }
      void start(){
            Thread th=new Thread(this);
            th.start();
      }
      @Override
      public void run() {
            System.out.println("Thread");
      }
}

您需要將Runnable實例傳遞給Thread類構造函數。

在您的情況下,請替換Thread th=new Thread(); 使用Thread th=new Thread(new NewClass())

當您使用Thread th=new Thread();創建Thread類實例時, Thread th=new Thread(); 調用Thread.run()方法的默認實現(不執行任何操作)。

因此,您需要在已正確完成的實現類(您的情況下為NewClass run()覆蓋run()方法。 但是您還需要使用Thread th=new Thread(new NewClass())向Thread類構造函數指定實現類實例。

您正在啟動一個新線程,但是該線程實際上沒有做任何事情。 新線程與它所啟動的類或該類所包含的代碼沒有任何關系。

實現Runnable時,通常通過創建一個帶有該Runnable作為參數的線程來執行它。

Runnable myRunnable = new NewClass();
Thread myThread = new Thread( myRunnable );`
myThread.start(); // will execute myRunnable.run() in background

或使用執行器

Executor myExecutor = new SheduledThreadPoolExecutor(NUM_OF_PARALLEL_THREADS);
Runnable myRunnable = new NewClass();
myExecutor.execute(myRunnable); // will execute myRunnable.run() in background as soon as one of the parralel threads is available

您的Thread類是與主類不同的類。

    public class ThreadClass implements Runnable {
        @Override
        public void run() {
            System.out.println("Thread");
        }
    }

    public class MainClass {
        public static void main(String[] agrg) {
            ThreadClass t = new ThreadClass();
            Thread th = new Thread(t);
            th.start();
        }

    }

如前所述,沒有人可以運行您的“運行”方法。 您可以擴展Thread並可以要求run方法僅通過啟動Thread來完成工作

public class NewClass extends Thread{
    public static void main(String[] agrg){
       NewClass n =new NewClass();
       n.start();
    }
    @Override
    public void run() {
       System.out.println("Thread");
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM