循环多个线程

时间:2017-10-12 19:46:34

标签: java

现在我正试图让我的头脑和并发, 所以我试图让多个线程一起计数到1000。 示例:线程1 = 0,线程2 = 1.线程3 = 2,依此类推 正如您将在代码中看到的,我实现了Runnable接口并启动了线程。 我能看到的是,即使我使用同步方法,每个线程也仅为自己启动循环。 这是循环"类"

 private String threadname;
    private int counter;

    Task3(String threadname,int counter) {
        this.threadname = threadname;
        this.counter =counter;

    }

    private synchronized void compute(int i) {
    try {

        // "simulate" computation
        System.out.println(threadname);
        Thread.sleep(100);
        System.out.println(" " + i);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

    public void run() {
        for(int i=0; i <= counter;i++)
            compute(i);
    }

在这个类中,我用一个for循环开始4个线程,并给方法提供参数,这些参数只是线程名称和它们应该计算的频率......

for(int i=0; i<=3;i++){
        Runnable r =new Thread(new Task3("Thread"+i,1000));
        Thread t = new Thread(r);
        t.start();
}

提前致谢

1 个答案:

答案 0 :(得分:2)

说明

Synchronized仅表示在进入方法之前确保线程等待,直到另一个线程完成执行此方法。这意味着只有一个一次 这个synchronized方法。

这可以在使用非原子操作时阻止奇怪的行为。例如,线程捕获过时的值,认为它们是最新的。

解决方案

如果您希望所有线程都在一起计算,则需要某种共享资源,即计数器。目前,每个主题都有他的自己的计数器。您需要总共一个计数器共享

快速而肮脏的方法是制作计数器static。但是你可以用这样的设计做得更好:

管理线程的类:

public class Demo {
    public static void main(String[] args) {
        Demo demo = new Demo();

        for (int i = 0; i < 3; i++) {
            Counter counter = new Counter(demo, 1000);
            counter.start();
        }
    }

    // Provide a shared resource for all threads
    private int sharedCounter = 0;

    // Provide a count method for all threads
    // which is synchronized to ensure that no
    // strange behavior with non-atomic operations occurs
    public synchronized void count() {
        sharedCounter++;
    }
}

Thread类:

public class Counter extends Thread {
    private Demo mDemo;
    private int mAmount;

    public Counter(Demo demo, int amount) {
        // Remember the shared resource
        mDemo = demo;
        mAmount = amount;
    }

    @Override
    public void run() {
        for (int i < 0; i < mAmount; i++) {
            // Call the count method provided
            // by the shared resource
            mDemo.count();

            // Sleep some millis
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
相关问题