同时启动线程并争论全局变量

发布于 2025-01-15 10:34:25 字数 1736 浏览 2 评论 0原文

我试图了解如何实现争论全局变量的线程。在我的实现中,我创建了 2 个变量,我想要 4 个线程(例如)通过递减来争议它。

第一个问题是我实现的消费方式始终遵循顺序(第一个线程减少片状冰淇淋,第二个线程减少巧克力冰淇淋)。

有什么办法可以改进这个规则吗?

我不想知道使用 CountDownLatch 的最佳位置在哪里

public class IceCream implements Runnable {

    private static int flake = 1;
    private static int chocolate = 1;
    @Override
    public void run() {
        buyIceCream();
        
    }   
    
    private void synchronized buyIceCream() {
try {
            
            if(IceCream.flake>0) {
                System.out.println("");
                System.out.println("successfully purchased " +Thread.currentThread().getName());
                Thread.sleep(200);
                IceCream.flake--;
                System.out.println("");             
            }
            else if(IceCream.chocolate>0) {
                System.out.println("");
                System.out.println("successfully purchased " +Thread.currentThread().getName());
                Thread.sleep(200);
                IceCream.chocolate--;
                System.out.println(""); 
            }
            else {
                System.out.println("No more ice cream " +Thread.currentThread().getName());
            }
        }
            catch(Exception e) {
                
            }       
        
    }
}
public static void main(String[] args) throws InterruptedException {
            IceCream c = new IceCream();
            Thread[] t = new Thread[4]; 
            for(int i = 0; i<t.length; i++) {
                t[i] = new Thread(c);
                t[i].setName("Kid"+ i);
                t[i].start();
                t[i].join();
                
            }
    
        }

I'm trying to understand how to implement Threads disputing global variables. In my implementation I created 2 variables and I want 4 Threds (e.g.) to dispute it by decrementing.

The first problem is that the way I implemented to consume will always follow an order (first Thread decrements the flake ice cream and the second Thread decrements the chocolate ice cream).

Is there any way to improve this rule?

And I wouldn't want to know what would be the best place to use CountDownLatch

public class IceCream implements Runnable {

    private static int flake = 1;
    private static int chocolate = 1;
    @Override
    public void run() {
        buyIceCream();
        
    }   
    
    private void synchronized buyIceCream() {
try {
            
            if(IceCream.flake>0) {
                System.out.println("");
                System.out.println("successfully purchased " +Thread.currentThread().getName());
                Thread.sleep(200);
                IceCream.flake--;
                System.out.println("");             
            }
            else if(IceCream.chocolate>0) {
                System.out.println("");
                System.out.println("successfully purchased " +Thread.currentThread().getName());
                Thread.sleep(200);
                IceCream.chocolate--;
                System.out.println(""); 
            }
            else {
                System.out.println("No more ice cream " +Thread.currentThread().getName());
            }
        }
            catch(Exception e) {
                
            }       
        
    }
}
public static void main(String[] args) throws InterruptedException {
            IceCream c = new IceCream();
            Thread[] t = new Thread[4]; 
            for(int i = 0; i<t.length; i++) {
                t[i] = new Thread(c);
                t[i].setName("Kid"+ i);
                t[i].start();
                t[i].join();
                
            }
    
        }

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

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

发布评论

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

评论(1

绅刃 2025-01-22 10:34:25

这是一个错误:

t[i].start();
t[i].join();

join() 调用在线程结束之前不会返回,因此您的程序永远不会允许多个线程同时运行。您可以通过编写两个单独的循环来修复错误。第一个创建并启动所有线程,然后第二个连接所有线程。

for(int i = 0; i<t.length; i++) {
    t[i] = new Thread(c);
    t[i].setName("Kid"+ i);
    t[i].start();
}
for(int i = 0; i<t.length; i++) {
    t[i].join();    
}

这是另一个错误:

public void run() {
    buyIceCream();
}   
    
private void synchronized buyIceCream() {
    ...
}

将线程执行的所有操作包装在单个 synchronized 方法中是确保不允许两个线程同时运行的另一种方法。

至少,您应该从 synchronized 块中删除 sleep() 调用:

private void buyIceCream() {
    String message = "No more ice cream ";
    synchronized (this) {
        if(IceCream.flake>0) {
            IceCream.flake--;
            message = "Ice cream flake purchased by" + Thread.currentThread().getName();
        }
        else if(IceCream.chocolate>0) {
            IceCream.chocolate--;
            message = "Chocolate ice cream purchased by" + Thread.currentThread().getName();
        }
    }
    System.out.println(message);
    try {
        Thread.sleep(200);
    }
    catch(Exception e) {
        System.out.println("Never, EVER, completely ignore an exception.");
    }       
}

我还移动了 System.out.println()synchronized 块中调用,因为我知道任何单个调用打印的字符都不会与来自不同线程的单个调用打印的字符交错。 (请参阅https://stackoverflow.com/a/9459743/801894

This is a mistake:

t[i].start();
t[i].join();

The join() call does not return until the thread has ended, so your program will never allow more than one thread to run at the same time. You can fix the mistake by writing two separate loops. The first one creates and starts all of the threads, and then the second one joins all of them.

for(int i = 0; i<t.length; i++) {
    t[i] = new Thread(c);
    t[i].setName("Kid"+ i);
    t[i].start();
}
for(int i = 0; i<t.length; i++) {
    t[i].join();    
}

This is another mistake:

public void run() {
    buyIceCream();
}   
    
private void synchronized buyIceCream() {
    ...
}

Wrapping everything that a thread does inside a single synchronized method is another way to ensure that no two of your threads will be allowed to run at the same time.

At the very least, you should remove the sleep() calls from the synchronized block:

private void buyIceCream() {
    String message = "No more ice cream ";
    synchronized (this) {
        if(IceCream.flake>0) {
            IceCream.flake--;
            message = "Ice cream flake purchased by" + Thread.currentThread().getName();
        }
        else if(IceCream.chocolate>0) {
            IceCream.chocolate--;
            message = "Chocolate ice cream purchased by" + Thread.currentThread().getName();
        }
    }
    System.out.println(message);
    try {
        Thread.sleep(200);
    }
    catch(Exception e) {
        System.out.println("Never, EVER, completely ignore an exception.");
    }       
}

I also moved the System.out.println() call out of the synchronized block because I know that the characters printed by any single call will not be interleaved with characters printed by a single call from a different thread. (See https://stackoverflow.com/a/9459743/801894)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文