gpt4 book ai didi

java,为什么 thread.wait() 在我的代码中不起作用

转载 作者:行者123 更新时间:2023-12-01 18:15:25 24 4
gpt4 key购买 nike

我有一个剧本(线程)循环打印几段文本,并且有一个屏幕中断来打印紧急文本,当屏幕中断打印时,应该先等待剧本。截屏打印所有文本后,会通知剧本,剧本开始打印。

class ScreenPlay implements Runnable{

public synchronized void notifys() throws InterruptedException {
notify();
}

public synchronized void waits() throws InterruptedException {
wait();
}

public void run(){
for(int i=0; i<15; i++){
System.out.println(i);
try{
Thread.sleep(500);
}catch(InterruptedException e){
e.printStackTrace();
}
if( i == 14 ){
i = -1;
}
}
}
}

class ScreenBreak implements Runnable{
private ScreenPlay screenplay;

public ScreenBreak(ScreenPlay screenplay){
this.screenplay = screenplay;
}

public void run(){
try{
Thread.sleep(2000);
screenplay.waits();
}catch(InterruptedException e){
e.printStackTrace();
}
for(int i=0; i<5; i++){
System.out.println("@_" + i);
}
try{
Thread.sleep(5000);
screenplay.notifys();
}catch(InterruptedException e){
e.printStackTrace();
}
}

}

public class Waits {
public static void main(String[] args) {

ScreenPlay s = new ScreenPlay();
ScreenBreak sb = new ScreenBreak(s);
new Thread(s).start();
new Thread(sb).start();

}
}

输出显示“wait()”根本不起作用,剧本继续打印。 screenbreak 从不打印其文本。为什么?这里出了什么问题?

我修改了代码并且它可以工作。

class ScreenPlay implements Runnable{

private int waittime = 1050;
private boolean isPause = false;

public synchronized void setIsPause(boolean isPause){
this.isPause = isPause;
}

public synchronized void go() throws InterruptedException {
this.isPause = false;
notify();
}

public void run(){
for(int i=0; i<15; i++){
System.out.println(i);
try{
for(int j = 0; j < waittime/500 + 1; j++){
Thread.sleep(500);
synchronized(this){
if(isPause){
System.out.println("waiting");
wait();
}else{
System.out.println("...");
}
}
}
}catch(InterruptedException e){
e.printStackTrace();
}
if( i == 14 ){
i = -1;
}
}
}
}

class ScreenBreak implements Runnable{
private ScreenPlay screenplay;

public ScreenBreak(ScreenPlay screenplay){
this.screenplay = screenplay;
}

public void run(){
try{
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
screenplay.setIsPause(true);
try{
Thread.sleep(5000);
for(int i=0; i<5; i++){
System.out.println("@_" + i);
}
screenplay.go();
}catch(InterruptedException e){
e.printStackTrace();
}

}

}

public class Waits {
public static void main(String[] args) {

ScreenPlay s = new ScreenPlay();
ScreenBreak sb = new ScreenBreak(s);
new Thread(s).start();
new Thread(sb).start();
try{
Thread.sleep(15000);
}catch(InterruptedException e){
e.printStackTrace();
}
new Thread(sb).start();

}
}

最佳答案

ScreenBreak开始wait()时,没有人notify()它。对 notify() 的唯一调用是在 ScreenBreak 中,但它永远不会到达那里,因为它卡在 wait() 处。

建议:返回tutorial

关于java,为什么 thread.wait() 在我的代码中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29938764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com