开发者

How to Switch Threads

I have 2 threads. I need to switch between them by pressing a key.

Thread outputplayer = new Thread(PlayerOutput);
Thread outputplaylist = new Thread(PlaylistOutput);


outputplayer.Start(player);
outputplaylist.Start(player);
outputplaylist.Suspend();


        while (true)
        {
            if (changePlaylist)
            {
                if (playlist)
                {
                    changePlaylist = false;

                    outputplaylist.Resume();
                    outputplayer.Suspend();
    开发者_如何学JAVA            }
                else
                {
                    changePlaylist = false;

                    outputplayer.Resume();
                    outputplaylist.Suspend();
                }
            }
            HandleInput(player);
        }

I tried this, but it doesnt switch always.

When I press a key, first thread should stop/pause and second thread should start execute. When I press key again, second thread should stop/pause and first thread should start execute. And so on. 1 => 2 => 1 => 2 ...

What should I do?


Do not ignore the Obsolete warnings on the Suspend and Resume methods. They were obsoleted for this exact reason. The exact place in code where they will freeze is completely unpredictable. Quite bad news if that's inside a lock statement. You've also created a time slot where both will be running.

Don't use threads for this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜