簡體   English   中英

Java - 創建一個新線程

[英]Java - creating a new thread

我是線程的新手。 我想創建一些與主線程分開工作的簡單函數。 但它似乎不起作用。 我只想創建新線程並在那里獨立於主線程上發生的事情做一些事情。 這段代碼可能看起來很奇怪,但到目前為止我沒有太多的線程經驗。 你能解釋一下這有什么問題嗎?

  public static void main(String args[]){
      test z=new test();

      z.setBackground(Color.white);

      frame=new JFrame();
      frame.setSize(500,500);
      frame.add(z);
      frame.addKeyListener(z);
      frame.setVisible(true);

      one=new Thread(){
          public void run() {
              one.start();
              try{
                  System.out.println("Does it work?");
                  Thread.sleep(1000);
                  System.out.println("Nope, it doesnt...again.");
              } catch(InterruptedException v){System.out.println(v);}
          }
      };
  }

您正在線程的run方法中調用one.start()方法。 但是run方法只會在線程已經啟動時被調用。 改為這樣做:

one = new Thread() {
    public void run() {
        try {
            System.out.println("Does it work?");

            Thread.sleep(1000);

            System.out.println("Nope, it doesnt...again.");
        } catch(InterruptedException v) {
            System.out.println(v);
        }
    }  
};

one.start();

你可以這樣做:

    Thread t1 = new Thread(new Runnable() {
    public void run()
    {
         // code goes here.
    }});  
    t1.start();

目標是編寫代碼在一個地方調用 start() 和 join() 。 參數匿名類是一個匿名函數。 new Thread(() ->{})

new Thread(() ->{
        System.out.println("Does it work?");
        Thread.sleep(1000);
        System.out.println("Nope, it doesnt...again.");       
}){{start();}}.join();

在匿名類的主體中有調用 start() 的實例塊。 結果是 Thread 類的一個新實例,稱為 join()。

你需要做兩件事:

  • 啟動線程
  • 在繼續之前等待線程完成(死亡)

IE

one.start();
one.join();

如果你不start()它,什么都不會發生——創建一個線程不會執行它。

如果您不join)它,您的主線程可能會在另一個線程被安排執行之前完成並退出,並且整個程序退出。 如果你不加入它,它是否運行是不確定的。 新線程通常可能會運行,但有時可能不會運行。 最好確定一下。

如果您想創建更多線程,在上述情況下,您必須在 run 方法中重復代碼或至少重復調用其中的某個方法。

試試這個,這將幫助您根據需要多次調用。 當您需要從多個地方多次執行運行時,這將很有幫助。

class A extends Thread {
    public void run() {
             //Code you want to get executed seperately then main thread.       
    }
     }

主班

A obj1 = new A();
obj1.start();

A obj2 = new A();
obj2.start();

run()方法由start()調用。 這會自動發生。 你只需要調用start() 有關創建和調用線程的完整教程,請參閱我的博客http://preciselyconcise.com/java/concurrency/a_concurrency.php

由於剛剛針對此關閉了一個新問題:您不應該自己創建Thread對象。 這是另一種方法:

public void method() {
    Executors.newSingleThreadExecutor().submit(() -> {
        // yourCode
    });
}

不過,您可能應該在調用之間保留執行程序服務。

創建線程有幾種方式

  1. 通過擴展Thread類 >5
  2. 通過實現Runnable接口 - > 5
  3. 通過使用ExecutorService接口 - >=8

更簡單的方法可以是:

new Thread(YourSampleClass).start();    

請試試這個。 在您查看我的解決方案后,您將完全理解所有內容。

java中只有兩種創建線程的方法

帶有可運行的工具

class One implements Runnable {
@Override
public void run() {
    System.out.println("Running thread 1 ... ");
}

與擴展線程

class Two extends Thread {
@Override
public void run() {
    System.out.println("Running thread 2 ... ");
}

你的主要課程在這里

public class ExampleMain {
public static void main(String[] args) {

    One demo1 = new One();
    Thread t1 = new Thread(demo1);
    t1.start();

    Two demo2 = new Two();
    Thread t2 = new Thread(demo2);
    t2.start();
}

}

暫無
暫無

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

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