JAVA - 使10个线程同时运行以增加计数器1-10

Rah*_*tia 0 java multithreading

我需要JAVA中的10个线程同时运行以从1-10增加计数器.

我有代码工作.但是,计数器总是处于不同的顺序.

public class Counter
{

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

    }
}

public class Count implements Runnable {
    int n=1;

    @Override
    public void run() {
        System.out.println(n++);
    }

    public void showOutput(){
        System.out.println(n++);
    }

}
Run Code Online (Sandbox Code Playgroud)

输出示例:2 4 3 1 5 9 8 6 7 10

Dar*_*usz 5

线程是异步的并且独立工作.除非使用了某些同步方法,否则不保证在不同线程中执行任何命令的任何顺序.你的代码运行正常.