Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java多线程/在循环中启动线程_Java_Multithreading - Fatal编程技术网

Java多线程/在循环中启动线程

Java多线程/在循环中启动线程,java,multithreading,Java,Multithreading,有人能帮我解决这个多线程问题吗 程序应该使用一个公共资源启动三个线程。每个线程都应该打印递增的计数值。下面提到了示例输出。其中T1、T2和T3为螺纹 T1 T2 T3 1 2 3 4 5 6 7 8 9 我当前的代码: public class RunnableSample implements Runnable { static int count = 0; public void run() { synchroni

有人能帮我解决这个多线程问题吗

程序应该使用一个公共资源启动三个线程。每个线程都应该打印递增的计数值。下面提到了示例输出。其中T1、T2和T3为螺纹

T1  T2  T3

1   2   3    

4   5   6

7   8   9
我当前的代码:

public class RunnableSample implements Runnable {
    static int count = 0;

    public void run() {
        synchronized (this) {
            count++;
            System.out.println(
                "Current thread : Thread name :" + Thread.currentThread().getName() 
                + " Counter value :" + count
            );
        }
    }
}

//main method with for loop for switching between the threads
public class ThreadInitiator {
    public static void main(String[] args) {
        RunnableSample runnableSample = new RunnableSample();

        Thread thread1 = new Thread(runnableSample, "T1");
        Thread thread2 = new Thread(runnableSample, "T2");
        Thread thread3 = new Thread(runnableSample, "T3");

        for (int i = 0; i < 9; i++) {
            thread1.start();
            thread2.start();
            thread3.start();
        }
    }
}
public类RunnableSample实现Runnable{
静态整数计数=0;
公开募捐{
已同步(此){
计数++;
System.out.println(
“当前线程:线程名称:”+thread.currentThread().getName()
+“计数器值:”+计数
);
}
}
}
//使用for循环在线程之间切换的主要方法

公共类线程启动器{ 公共静态void main(字符串[]args){ RunnableSample RunnableSample=新的RunnableSample(); Thread thread1=新螺纹(runnableSample,“T1”); 螺纹2=新螺纹(可运行示例,“T2”); 螺纹3=新螺纹(可运行示例,“T3”); 对于(int i=0;i<9;i++){ thread1.start(); thread2.start(); thread3.start(); } } }
创建一个同步方法来增加值。当一个方法被标识为已同步时,一次只能有一个线程访问它,其他线程等待初始线程完成方法执行,然后才能访问该方法


请检查

酷!到目前为止你试过什么?@Nicolas这是我的密码。它在执行主函数公共类ThreadInitiator{public static void main(String[]args){RunnableSample RunnableSample=new RunnableSample();Thread thread1=new Thread(RunnableSample,“T1”);thread2=new Thread(RunnableSample,“T2”);Thread thread3=new Thread(RunnableSample,“T3”);对于(inti=0;i<9;i++){thread1.start();thread2.start();thread3.start();}}}}在main方法中如何执行类似操作。