如何同时执行三个线程



这是我尝试过的代码,但我的主类不在那里,因为我不知道如何使用那个

//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);
     }}
}

首先覆盖 run 方法,然后在 main() 中创建线程类的对象并调用启动方法。

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();
    }
}

无论你写什么都是不完整的代码,要创建一个线程,你需要扩展 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()

我不会复制粘贴代码,而是将您指向官方文档,您可以在其中找到一些示例。

下面给出的示例程序。由于没有同步代码,因此三个线程的输出是混合的

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();
    }
}
}

最新更新