简体   繁体   English

定时器死锁问题

[英]Timer Deadlock Issue

I'm trying to set up a timer thread that once a second increments a counter and outputs the result to the terminal. 我正在尝试设置一个计时器线程,每秒一次递增计数器并将结果输出到终端。

public class SecondCounter implements Runnable
{
private volatile int counter;
private boolean active;
private Thread thread;

public SecondCounter()
{
    counter = 0;
    active = true;
    thread = new Thread(this);
    thread.start();
}

public int getCount()
{
    return counter;
}

public void run()
{
    while(active)
    {
        try {
            Thread.sleep(1000);
        } catch(InterruptedException ex) {ex.printStackTrace();}

        synchronized(this)
        {
            System.out.print(++counter+" ");
            try{
                notifyAll();
                wait();
            } catch(InterruptedException ex) {ex.printStackTrace();}
        }
    }
}

Then, I have another method in the class called messagePrinter() that takes in an integer, creates a new thread, and monitors the main timer thread to see when a multiple of that int is on the count: 然后,我在类中有另一个方法,叫做messagePrinter(),它接受一个整数,创建一个新线程,并监视主计时器线程,看看该int的多个是在count上的:

public synchronized void messagePrinter(final int x)
{
    Runnable mp = new Runnable()
    {
        public void run()
        {
            while(active)
            {
                synchronized(this)
                {
                    try {
                        while(counter%x != 0 || counter == 0 )
                        {
                            notifyAll();
                            wait();
                        }
                        System.out.println("\n"+x+" second message");
                        notifyAll();
                    } catch(InterruptedException ex) {ex.printStackTrace();}
                }
            }
        }
    };
    new Thread(mp).start();
}

I have tried messing around with wait() and notifyAll() quite a bit but every combination I have tried results in both threads entering a wait state and causing deadlock. 我已经尝试过使用wait()和notifyAll(),但我尝试过的每个组合都会导致两个线程进入等待状态并导致死锁。 Or, the timer thread will hog all of the thread time and never give the messagePrinter a chance to check what the count is currently at. 或者,计时器线程将占用所有线程时间,并且永远不会给messagePrinter提供检查当前计数的机会。

Here is what the output should look like: 这是输出应该是什么样子:

1 2 3
3 second message
4 5 6
3 second message

I am aware that the timer is probably not going to time to be perfectly 1 second per tick with this method, but the point of the exercise was to get some experience with passing information between threads. 我知道计时器可能没有时间用这种方法完美地每秒1秒,但练习的目的是获得一些在线程之间传递信息的经验。

Here is my main file: 这是我的主要文件:

public class Main2
{
    public static void main(String[] args)
    {
        SecondCounter c = new SecondCounter();
        c.messagePrinter(3);
    }
}

Anyone with some threading experience care to give me some insight on where I am going wrong? 任何有线程经验的人都会给我一些关于我哪里出错的见解?

EDIT: I have converted my integer counter to an atomic integer, and I changed the messagePrinter to be synchronized on "SecondCounter.this" instead of "this". 编辑:我已将整数计数器转换为原子整数,并将messagePrinter更改为在“SecondCounter.this”而不是“this”上同步。 It's working now! 它现在正在工作! Mostly anyway, it's printing "x second message" about thirty times a loop when there are multiple messagePrinters. 无论如何,当有多个messagePrinters时,它正在打印“x second message”大约三十次循环。 I think I can fix that though. 我想我可以解决这个问题。

I have it working now, here is my working code: 我现在有工作,这是我的工作代码:

import java.util.concurrent.atomic.AtomicInteger;

public class SecondCounter implements Runnable
{
private volatile AtomicInteger counter;
private boolean active;
private boolean printed;
private Thread thread;

public SecondCounter()
{
    counter = new AtomicInteger(0);
    active = true;
    thread = new Thread(this);
    thread.start();
}



public void run()
{

    while(active)
    {
        try {
            Thread.sleep(1000);
        } catch(InterruptedException ex) {ex.printStackTrace();}

        synchronized(this)
        {
            System.out.print(counter.incrementAndGet()+" ");    
            printed = false;
            try{
                this.notify();
                this.wait();
            } catch(InterruptedException ex) {ex.printStackTrace();}
        }
    }
}

public synchronized void messagePrinter(final int x)
{
    Runnable mp = new Runnable()
    {
        public void run()
        {
            while(active)
            {
                synchronized(SecondCounter.this)
                {
                    try {
                        while(counter.get()%x != 0 || counter.get() == 0 )
                        {
                            SecondCounter.this.notify();
                            SecondCounter.this.wait();
                        }
                        if(!printed)
                        {
                            System.out.println("\n"+x+" second message");
                            printed = true;
                        }
                        SecondCounter.this.notify();
                        SecondCounter.this.wait();
                    } catch(InterruptedException ex) {ex.printStackTrace();}
                }
            }
        }
    };
    new Thread(mp).start();
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM