簡體   English   中英

如何同時執行三個線程?

[英]How to execute three thread simultaneously?

這是我嘗試的代碼,但是我的主類不在那兒,因為我不知道如何使用該代碼

//first thread

class firstthread extends Thread
{
   public void run(){
     for(int i=0;i<1000;i++)
     {
          System.out.println(i);
     }}
}

//second thread

class secondthread extends Thread
{
   public void run(){
     for(int i=0;i<1000;i++)
     {
          System.out.println(i);
     }}
}

無論您編寫的是不完整的代碼,要創建線程,都需要擴展Thread類或實現Runnable接口,然后重寫其public void run()方法。

要創建線程,您需要重寫方法public void run

然后,要啟動線程,您需要調用其start()方法。

一個簡單的完整示例

class MyThread extends Thread {
   String name;
   public void run(){
      for(int i=0;i<1000;i++) {
         System.out.println("Thread name :: "+name+" : "i);
     }
   }
}
class Main{
    public static void main(String args[]){
        MyThread t1 = new MyThread();
        t1.name = "Thread ONE";
        MyThread t2 = new MyThread();
        t2.name = "Thread TWO";
        MyThread t3 = new MyThread();
        t3.name = "Thread THREE";
        t1.start();
        t2.start();
        t3.start();
    }
}

首先覆蓋run方法,然后在main()中創建線程類的對象,然后調用start方法。

public static void main(String[] args) {
    for (int i = 0; i < 3; i++) {
        new Thread() {
            public void run() {
                for(int y=0;y<1000;y++)
                 {
                      System.out.println(y);
                 }
            };
        }.start();
    }
}

您不能只在類主體中放入一些代碼。

您需要一個方法將代碼放入其中,如果是線程,則該方法為run()

除了將代碼復制粘貼外,我還將帶您到官方文檔 ,您可以在其中找到一些示例。

下面給出了示例程序。 由於沒有同步代碼,因此三個線程混合輸出

public class ThreadTest implements Runnable{

@Override
public void run() {
    System.out.print(Thread.currentThread().getId() + ": ");
    for(int i=0;i<100;i++)
        System.out.print(i + ", ");
    System.out.println();

}
public static void main(String[] args) {
    for(int i=0;i<3;i++){
        new Thread(new ThreadTest()).start();
    }
}
}

暫無
暫無

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

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