【问题标题】:Concurrent Threads并发线程
【发布时间】:2016-05-21 22:11:35
【问题描述】:

我完成了一些基本代码来为一个任务分配 2 个线程。但是我必须制作两个版本,一个可以让两个线程同时调用任务,一个永远不会并发。但我什至不确定我制作了哪个版本,更不用说我将如何识别它了。

import java.util.*;
public class Week5
{
    static int sharedData = 0;
    public static void main(String[] args)
    {
        atomic myAtomic = new atomic();

        Thread thread1 = new Thread(myAtomic);
        thread1.setName("thread 1");

        Thread thread2 = new Thread(myAtomic);
        thread2.setName("thread 2");

        thread1.start();
        thread2.start();

        try
        {
            thread1.join();
            thread2.join();
        }
        catch(InterruptedException e)
        {
            System.out.println("Thread " + Thread.currentThread().getName() + "was interrupted");
        }
        System.out.println("sharedData = " + sharedData);
        System.out.println("Exiting Main function from: " + Thread.currentThread().getName());
    }
    public static class atomic implements Runnable
    {
        public synchronized void run()
        {
            System.out.println("Starting 'Atomic' Function from: " + Thread.currentThread().getName());
        sharedData = sharedData + 1;

            System.out.println("Exiting 'Run' function from: " + Thread.currentThread().getName());
        }
    }
}

【问题讨论】:

  • 那么你的问题是什么?
  • 这是如何识别它是否可以同时运行。我道歉;为了确保我从另一个来源复制/粘贴的站点的间距和一切都正确,并错误地在代码后留下了最后几行。当然,那是我的问题更明显的措辞。
  • @Cordre 不在这里解释。未来的读者想通过阅读您发布的内容来了解​​您的问题。请编辑您的帖子

标签: java multithreading concurrency


【解决方案1】:

您的线程永远不能同时运行相同的任务,因为run() 方法是同步的,这意味着同一对象一次只能有一个线程进入。如果它没有同步,两个线程可能会同时执行它。

【讨论】:

  • 完美。所以我只需要删除那个单词,然后它们就可以同时运行了吗?此外,老师要求将类命名为 Atomic 同时禁止使用 atomic int,这也是一个残酷的玩笑。把我赶走,让我走错了路。
  • @Cordre 没错。并且该类正在对您的情况进行原子更新,至少在您删除 synchronized 之前。那么它肯定会令人困惑。
  • @Cordre,删除那个单词,它们将被允许同时运行,但不管它们是否真的确实运行同时是另一个问题。您的 run() 方法很短。无法保证当您的 main() 例程调用 thread1.start() 时,线程不会在 main() 有机会启动 thread2 之前运行完成。
猜你喜欢
  • 2012-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 2011-09-14
  • 2015-02-12
  • 2014-11-02
相关资源
最近更新 更多