Java单线程堵塞解决方案
Java单线程阻塞解决方案
转至:http://www.blogjava.net/unser/archive/2008/01/09/174052.html
一个Feed提取小程序,但有时由于Feed长时间无响应,所以需要去判断是否超时,以下的程序
主线程:
1
package test.thread;
2
3
import com.sun.syndication.feed.synd.SyndFeed;
4
5
public class RssThread extends Thread {
6
7
public void run() {
8
while(true)
9
{
10
try
11
{
12
13
System.out.println("start");
14
15
String[] str = new String[]{"http://del.icio.us/rss/geneboy",
16
"http://picasaweb.google.com/data/feed/base/user/icyleaf.cn",
17
"http://feeds.qzone.qq.com/cgi-bin/cgi_rss_out?uin=414680"};
18
19
for( int i = 0 ; i < str.length ; i++ )
20
{
21
System.out.println("url = " + str[i]);
22
23
RssUtil ru = new RssUtil();
24
ru.setUrl(str[i]);
25
ru.start();
26
27
while(true)
28
{
29
sleep(2000);
30
SyndFeed feed = ru.getFeed();
31
System.out.println("feed = " + (feed != null ? "ok" : "timeOut"));
32
33
if ( feed == null )
34
{
35
sleep(10000);
36
37
feed = ru.getFeed();
38
System.out.println("second feed = " + (feed != null ? "ok" : "timeOut"));
39
}
40
41
if ( feed == null )
42
{
43
break;
44
}
45
else
46
{
47
System.out.println("处理不null");
48
break;
49
}
50
}
51
}
52
53
System.out.println("end");
54
55
sleep(2000);
56
57
}catch(Exception e)
58
{
59
//e.printStackTrace();
60
}
61
}
62
}
63
64
public static void main(String[] args)
65
{
66
RssThread rss = new RssThread();
67
rss.start();
68
}
69
}
70
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
RssUtil:负责提取Rss
1
package test.thread;
2
3
import java.net.URL;
4
5
import org.apache.commons.logging.Log;
6
import org.apache.commons.logging.LogFactory;
7
8
import com.sun.syndication.feed.synd.SyndFeed;
9
import com.sun.syndication.io.SyndFeedInput;
10
import com.sun.syndication.io.XmlReader;
11
12
/**
13
* Rss相关
14
*
15
* @author Administrator
16
*
17
*/
18
public class RssUtil extends Thread {
19
20
private String url;
21
22
private SyndFeed feed;
23
24
private static final Log logger = LogFactory.getLog(RssUtil.class);
25
26
public void run() {
27
28
feed = getFeed(url);
29
}
30
31
/**
32
* 获得Feed
33
*
34
* @param url
35
* @return
36
*/
37
public SyndFeed getFeed(String url) {
38
try
39
{
40
URL feedUrl = new URL(url);
41
SyndFeedInput input = new SyndFeedInput();
42
43
SyndFeed feed = input.build(new XmlReader(feedUrl));
44
45
return feed;
46
47
} catch (Exception ex) {
48
//ex.printStackTrace();
49
}
50
51
return null;
52
}
53
54
public SyndFeed getFeed() {
55
return feed;
56
}
57
58
public void setFeed(SyndFeed feed) {
59
this.feed = feed;
60
}
61
62
public String getUrl() {
63
return url;
64
}
65
66
public void setUrl(String url) {
67
this.url = url;
68
}
69
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<!--EndFragment-->