我做了这个简单的线程减法程序。 它工作正常,但在输出结束时,它会给出3个随机值。我不知道如何防止这一点,任何想法? 我还必须计算每个线程减少了多少次计数器。有人可以帮助我吗?Simple MultiThreads程序错误输出
public class ThreadsExample implements Runnable {
static int counter = 100000;
static long time;
static long endtime;
static float finaltime;
static int value;
static void incrementCounter() {
System.out.println(Thread.currentThread().getName() + ": " + counter);
counter--;
}
@Override
public void run() {
time = System.nanoTime();
while (counter >= 0) {
incrementCounter();
}
endtime = System.nanoTime() - time;
finaltime = endtime;
System.out.println(finaltime/1000000000 + " sekundy");
}
public static void main(String[] args) throws InterruptedException {
ThreadsExample threads = new ThreadsExample();
Thread thread1 = new Thread(threads);
Thread thread2 = new Thread(threads);
Thread thread3 = new Thread(threads);
Thread thread4 = new Thread(threads);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
if (counter <= 0) {
System.out.println("Thread 1,2,3,4^^^");
}
}
}
首先,您将ThreadExample的同一个实例传递给每个线程。这可能会导致一些内部状态异常。尝试为每个线程构造函数创建一个新的ThreadsExample。它看起来像每个ThreadsExample将基本上同时停止,因为“counter”是静态的,并且所有实例都会在基本相同的确切时间检测到“counter <0”。这是预期的吗?或者你想让每个线程管理自己的独立计数器? – pacifier21
你没有任何形式的同步。因此,每个线程可能会读取一些值'> 0'并减少'counter',这样'counter'就会以某个值<<0结束。此外,每个线程都会将'finaltime'设置为一个值,您在那里有一个竞争条件。 – Turing85