作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个打开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"
}
}
最佳答案
中断线程的一个技巧是切断对编写器的输入。这个例子说明了这个概念:
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'
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()
关于multithreading - 如何在Grails中的线程中中断HttpUrlConnection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31732468/
我是一名优秀的程序员,十分优秀!