【发布时间】: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