gpt4 book ai didi

multithreading - 如何在Grails中的线程中中断HttpUrlConnection?

转载 作者:行者123 更新时间:2023-12-02 14:30:46 25 4
gpt4 key购买 nike

我有一个打开URL连接的线程。我想中断线程时遇到问题。不抛出Interrupted Exception。

这段代码在我的线程中运行

public void run() {
try {
final HttpURLConnection connection =new URL(url).openConnection()
connection.setReadTimeout(600000)
connection.setRequestMethod("POST")
connection.outputStream.withWriter { Writer writer ->
writer << requestxml
} catch (InterruptedException ie) {
println "interrupted"
} catch (Exception e) {
println "other error"
}
}

当我停止线程theThread.interrupt()时,请求不会停止。
当我使用一些伪代码(例如while(true)Thread.sleep(500))时,中断正常工作。

我究竟做错了什么?

最佳答案

中断线程的一个技巧是切断对编写器的输入。这个例子说明了这个概念:

class RandomByteArrayInputStream extends InputStream {
def rand = new Random()
def isClosed = false

int read() {
if(isClosed) {
-1
} else {
rand.nextInt((90 - 65) + 1) + 65;
}
}

void close() {
isClosed = true
}
}

def input = new RandomByteArrayInputStream()
def output = new ByteArrayOutputStream()

println 'Starting background thread.'
def t = Thread.start {
output.withWriter {w ->
w << input
}
println 'Oh darn, ran out of input.'
}

println 'Sleeping...'
Thread.currentThread().sleep(5000)
println 'Awake! Closing input stream.'
input.close()
println 'Done'

在上面的示例中,RandomByteArrayInputStream模拟了一个大型(实际上是无尽的)数据源。休眠之后,主线程关闭RandomByteArrayInputStream,这导致写入器停止写入,这导致线程结束并停止。

尽管HttpURLConnection超时起作用,但是可以使用类似的概念来中断对此类连接的写入:
class ClosableByteArrayInputStream extends ByteArrayInputStream {
def isClosed = false

public ClosableByteArrayInputStream(String string) {
super(string as byte[])
}

int read() {
isClosed ? -1 : super.read()
}

void close() {
isClosed = true
}
}

class MyThread extends Thread {
private InputStream inputStream

def url
def requestxml

public void run() {
final HttpURLConnection connection = url.openConnection()
connection.setReadTimeout(600000)
connection.setRequestMethod("POST")
connection.doOutput = true
inputStream = new ClosableByteArrayInputStream(requestxml)

connection.outputStream.withWriter { Writer writer ->
writer << inputStream
}
}

public void interrupt() {
inputStream?.close()
super.interrupt()
}
}

def t = new MyThread()
t.url = 'URL GOES HERE'.toURL()
t.requestxml = 'DATA GOES HERE'
t.start()

// Do whatever...

t.interrupt()

在这里,使用Thread的子类代替Runnable的实现,以便中断方法可以关闭从XML数据创建的输入流。

注意:我创建ClosableByteArrayInputStream是因为在ByteArrayInputStream上调用close方法无效。

关于multithreading - 如何在Grails中的线程中中断HttpUrlConnection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31732468/

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