gpt4 book ai didi

java - 线程没有在此代码中停止,有什么原因吗?

转载 作者:行者123 更新时间:2023-12-01 23:08:33 24 4
gpt4 key购买 nike

为什么在这段代码中消费者线程完成后,生产者线程没有被中断,也就是说它的流程没有停止?

class buffer{
int value;
public void consume()
{
System.out.println(value+" is consumed");

}
public void produce(int x)
{

value=x;
System.out.println(value+" is produced");


}


}
class producer extends Thread
{
buffer x;

public producer(buffer x)
{
this.x=x;
}
public void run()
{
for(int i=0;i<15;i++)
{
x.produce(i);

}

}
}
class consumer extends Thread
{
buffer x;
producer y;

public consumer(buffer x,producer y) {
super();
this.x = x;
this.y=y;
}

public void run()
{
for(int i=0;i<10;i++)
{
x.consume();
}
y.interrupt();
}
}
class tester
{
public static void main(String[] args) {

buffer x=new buffer();
producer z=new producer(x);
consumer y=new consumer(x,z);
y.start();
z.start();
}
}

最佳答案

作为Java tutorial on Thread interruption这里指出

It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

您没有专门执行任何操作来处理中断,因此当您调用时不会发生任何事情

y.interrupt();

关于java - 线程没有在此代码中停止,有什么原因吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22387608/

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