Java线程竞赛,更改System.out.println之后,代码弄乱了

发布于 2025-02-06 02:06:44 字数 2902 浏览 2 评论 0原文

我的程序只打印出一个获胜者,我的计划仍允许其他线程在打印时间时完成比赛。当我取出System.out.println行时,它会弄乱所有内容,我不知道如何以及为什么可能。

我正在使用可运行的和锁定语句,并且仍遇到问题。

线程

package com.company;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadThings implements Runnable {

Lock lock = new ReentrantLock();

private String ThreadName;
static boolean winner;
int position = 0;

public ThreadThings(String ThreadName) {
    this.ThreadName = ThreadName;
}


//Start of a thread
@Override
public synchronized void run() {

    lock.lock();

    long startTime = System.currentTimeMillis();

    for (int i = 1; i <= 100; i++) {
        System.out.println(ThreadName + " Meters " + i);
        this.position = i;
        //position++;


        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {


        }

        if ((position == 100) && (winner == false)) {
            System.out.println(ThreadName+ " wins");
            winner = true;
            System.out.println("Congrats " + ThreadName + " you are the winner");

        }


      /**  if ((position == 10) && (winner == true)) {

                System.out.println("Good Try " + ThreadName);
            }
**/
        }

    long stopTime = System.currentTimeMillis();

    long raceTime = stopTime - startTime;

    System.out.println(ThreadName + " Time is " + raceTime + " Minutes");
    // else {System.out.println("Thanks for running");   }

    lock.unlock();

    }


}

package com.company;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {

public static void main(String[] args) {

    Lock lock = new ReentrantLock();

    ThreadThings t1 = new ThreadThings("Abby");
    ThreadThings t2 = new ThreadThings("Brandon");
    ThreadThings t3 = new ThreadThings("Casey");
    ThreadThings t4 = new ThreadThings("David");
    ThreadThings t5 = new ThreadThings("Eddie");
    ThreadThings t6 = new ThreadThings("Frank");
    ThreadThings t7 = new ThreadThings("Gabby");
    ThreadThings t8 = new ThreadThings("Hannah");
    ThreadThings t9 = new ThreadThings("Indie");
    ThreadThings t10 = new ThreadThings("Jasmine");

    Thread Runner1 = new Thread(t1);
    Thread Runner2 = new Thread(t2);
    Thread Runner3 = new Thread(t3);
    Thread Runner4 = new Thread(t4);
    Thread Runner5 = new Thread(t5);
    Thread Runner6 = new Thread(t6);
    Thread Runner7 = new Thread(t7);
    Thread Runner8 = new Thread(t8);
    Thread Runner9 = new Thread(t9);
    Thread Runner10 = new Thread(t10);

    lock.lock();

    Runner1.start();
    Runner2.start();
    Runner3.start();
    Runner4.start();
    Runner5.start();
    Runner6.start();
    Runner7.start();
    Runner8.start();
    Runner9.start();
    Runner10.start();

    lock.unlock();

    }

}

I am having issues with my program printing out only one winner and still allowing the other threads to finish the race while printing their time. When I take out the System.out.println line it messes everything up and I have no idea how and why it is possible.

I am using the Runnable and lock statements and still running into the issue.

ThreadThings

package com.company;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadThings implements Runnable {

Lock lock = new ReentrantLock();

private String ThreadName;
static boolean winner;
int position = 0;

public ThreadThings(String ThreadName) {
    this.ThreadName = ThreadName;
}


//Start of a thread
@Override
public synchronized void run() {

    lock.lock();

    long startTime = System.currentTimeMillis();

    for (int i = 1; i <= 100; i++) {
        System.out.println(ThreadName + " Meters " + i);
        this.position = i;
        //position++;


        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {


        }

        if ((position == 100) && (winner == false)) {
            System.out.println(ThreadName+ " wins");
            winner = true;
            System.out.println("Congrats " + ThreadName + " you are the winner");

        }


      /**  if ((position == 10) && (winner == true)) {

                System.out.println("Good Try " + ThreadName);
            }
**/
        }

    long stopTime = System.currentTimeMillis();

    long raceTime = stopTime - startTime;

    System.out.println(ThreadName + " Time is " + raceTime + " Minutes");
    // else {System.out.println("Thanks for running");   }

    lock.unlock();

    }


}

Main

package com.company;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {

public static void main(String[] args) {

    Lock lock = new ReentrantLock();

    ThreadThings t1 = new ThreadThings("Abby");
    ThreadThings t2 = new ThreadThings("Brandon");
    ThreadThings t3 = new ThreadThings("Casey");
    ThreadThings t4 = new ThreadThings("David");
    ThreadThings t5 = new ThreadThings("Eddie");
    ThreadThings t6 = new ThreadThings("Frank");
    ThreadThings t7 = new ThreadThings("Gabby");
    ThreadThings t8 = new ThreadThings("Hannah");
    ThreadThings t9 = new ThreadThings("Indie");
    ThreadThings t10 = new ThreadThings("Jasmine");

    Thread Runner1 = new Thread(t1);
    Thread Runner2 = new Thread(t2);
    Thread Runner3 = new Thread(t3);
    Thread Runner4 = new Thread(t4);
    Thread Runner5 = new Thread(t5);
    Thread Runner6 = new Thread(t6);
    Thread Runner7 = new Thread(t7);
    Thread Runner8 = new Thread(t8);
    Thread Runner9 = new Thread(t9);
    Thread Runner10 = new Thread(t10);

    lock.lock();

    Runner1.start();
    Runner2.start();
    Runner3.start();
    Runner4.start();
    Runner5.start();
    Runner6.start();
    Runner7.start();
    Runner8.start();
    Runner9.start();
    Runner10.start();

    lock.unlock();

    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

洋洋洒洒 2025-02-13 02:06:45

您已经锁定了3件不同的东西,并且每个锁完全没有用。

您缺少的是,锁不是随机使事情正常工作的魔术小精灵灰尘。它们用于链接构造 - 如果两个不同的线程都尝试锁定相同的锁定对象,则会发生某些事情(EM之一将等待)。如果您做其他事情,那是没有用的。

无用的锁1 = Main中的锁定锁定,然后

创建一个锁,然后锁定。此锁没有与任何其他线程共享,因此什么都不做。

无用的锁定2 = threadthings.run()的锁

,再次与其他任何东西共享的锁。每个线程都有自己的锁,并将其锁定。这无济于事。

无用的锁3 = 同步

同步在实例方法上是语法糖,用于锁定上的整个方法主体。鉴于您正在制作10个新的螺纹对象,因此,这些锁定还没有其他锁定,因此,它们什么也不做。

修复程序

使一个单锁对象,并在任何地方使用它。请注意,您已经在这里降落的基本方法(在完成线程时要锁定并在完成后解锁),这意味着整个练习将以不同的方式没有用:您将有10个线程,但是10中的9个将在等待。换句话说,这只是一首歌和舞蹈的例程,什么都没有用 - 您不妨顺序执行10个任务,因为如果您修复了它,那正是您的代码所做的。

锁的真正工作方式

找到了需要同步的一件事,并使用锁来保护该部分,仅此而已。例如,我非常怀疑您是否需要thread.sleep() 锁定块,因为锁没有脱离。您的线程现在要等待10毫米,其他人也会等待,因为它们根本无法继续获取锁,因为您无法获得锁,因为您的睡眠线有它。

如果愿意,您可以在线程中锁定并解锁几次。这似乎是您想要的。

修复:

  1. 要么使用锁,使用同步。不是两个。
  2. 在一个对象上进行一个锁 - 同步,或在您的main中创建一个锁,然后将其传递到10个线程对象,以便它们可以锁定。
  3. 不要仅仅锁定run()的顶部,然后在末尾解锁,那么您的线程只是无用的练习。也许锁定并解锁乘数时间(即睡觉前解锁,在继续之前重新锁定)。

You've locked 3 different things, and every lock is completely useless.

The thing you're missing is that locks aren't magic pixie dust that just randomly makes things work. They serve to link constructs - if two different threads both try to lock the same lock object, something happens (one of em will wait). If you do anything else, it's useless.

Useless lock 1 = The lock in main

You create one lock, and then lock it. This lock is not shared with any other thread, and therefore, does nothing.

Useless lock 2 = The lock in ThreadThings.run()

Again, a lock that isn't shared with anything else. Each and every thread has its own lock, and locks it. This does nothing.

Useless lock 3 = synchronized

synchronized, on an instance method, is syntax sugar for locking the entire method body on this. Given that you're making 10 new ThreadThings object, yet again, these are locks nothing else is locking on, and thus, they do nothing.

The fix

Make a single lock object and use that everywhere. Note that the basic approach you've landed on here (which is to lock when you start a thread and unlock it when it is done) means that this entire exercise would then be useless in a different fashion: You'd have 10 threads, but 9 of the 10 will be waiting. In other words, it's just a song and dance routine that accomplishes nothing useful - you might as well just do the 10 tasks sequentially, because that's exactly what your code would do, had you fixed it.

How locks really work

Find the one thing that requires synchronization and use locks to guard just that section and nothing more. For example, I highly doubt you'd want Thread.sleep() within a locked block, as the lock isn't disengaged. Your threads now waits 10 millisecs, and so will the others, as they simply can't continue without acquiring the lock, which they can't, because your sleeping thread has it.

You can lock and unlock a couple of times in a thread if you like. That seems like what you're looking for.

Fixes:

  1. Either use locks, or use synchronized. Not both.
  2. Make one lock - either synchronized on one object, or create one lock in your main and pass it to the 10 ThreadThings objects so that they can lock on it.
  3. Don't just lock at the top of the run() and unlock at the end - then your threads are just a useless exercise. Perhaps lock and unlock multiply times (i.e. unlock before sleeping, re-lock before continuing).
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文