简体   繁体   English

如何同时执行三个线程?

[英]How to execute three thread simultaneously?

This is my code which i tried but my main class is not there because i don't know how to use that one 这是我尝试的代码,但是我的主类不在那儿,因为我不知道如何使用该代码

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

Whatever you have written is incomplete code, to create a thread you need to extend Thread class or implement Runnable interface and then override its public void run() method. 无论您编写的是不完整的代码,要创建线程,都需要扩展Thread类或实现Runnable接口,然后重写其public void run()方法。

To create a thread you need to override the method public void run 要创建线程,您需要重写方法public void run

Then to start the threads you need to call its start() method. 然后,要启动线程,您需要调用其start()方法。

A simple complete example 一个简单的完整示例

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

You can't just put some code in your class body. 您不能只在类主体中放入一些代码。

You need a method to have the code in, the method being run() in case of thread. 您需要一个方法将代码放入其中,如果是线程,则该方法为run()

Instead of copy-pasting the code, I'll point you to the official documentation where you can find some examples. 除了将代码复制粘贴外,我还将带您到官方文档 ,您可以在其中找到一些示例。

Sample program given below. 下面给出了示例程序。 Since there is no synchronization code, there output is mixed from the three threads 由于没有同步代码,因此三个线程混合输出

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