【问题标题】:Java Multi Threading / initiating threads in a loopJava多线程/在循环中启动线程
【发布时间】:2016-10-20 17:37:46
【问题描述】:

有人可以帮我解决这个多线程问题吗?

程序应该使用公共资源启动三个线程。每个线程都应该打印一个递增的计数值。示例输出如下所述。其中 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();
        }
    }
}

【问题讨论】:

  • 酷!到目前为止,您尝试过什么?
  • @Nicolas 这是我的代码。执行主函数时抛出异常

标签: java multithreading


【解决方案1】:

创建一个同步方法来增加值。当一个方法被标识为同步时,一次只有一个线程可以访问它,其他线程等待初始线程完成方法执行后才能访问该方法。

请查看How to synchronize a static variable among threads running different instances of a class in java?

【讨论】:

  • 公共类 ThreadInitiator { public static void main(String[] args) { RunnableSample runnableSample = new RunnableSample();线程 thread1 = new Thread(runnableSample, "T1");线程 thread2 = new Thread(runnableSample, "T2");线程 thread3 = new Thread(runnableSample, "T3"); for (int i = 0; i
  • 在main方法中怎么做这样的事情。
猜你喜欢
  • 2013-12-24
  • 1970-01-01
  • 2015-09-30
  • 1970-01-01
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
相关资源
最近更新 更多