2012-01-24 44 views
0

我想创建一个java类(线程),它可以ping twitter,如果没有连接,则等待连接并重新运行一些其他类和线程。 我有“ping”网站的代码,并且运行每个静态方法的方法都在我的Main类中。这是解决问题的好办法吗?在java中创建一个timeOut类

这里是代码的基本部分:

while (true){ 
try { 
final URLConnection connection = new URL(url).openConnection(); 
connection.connect(); 
} 
catch (Exception e) { 
    Thread.sleep(10000*t); 
if (url.matches(twitter1)){ 
     Thread method1= new Thread(Class1.method1); 
     method1.start(); 
}else if (url.matches(twitter2)){ 
     Thread method2 = new Thread(Class1.method2); 
     method2.start(); 
}else if (url.matches(twitter3)){ 
     Main.StaticMethod(); 
}else if (url.matches(twitter4)){ 
     Main.StaticMethod2(); 
}else if (url.matches(twitter5)){ 
     Main.StaticMethod3(); 
}else{ 
     System.out.println("Unknown URL"); 
} 
t=2^t; 
} 
} 
+0

[使用计时器](http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html) – AJG85

回答

0

您将如何定义“跑”类?一种方法是在timeOut类中存储对这些类的引用,然后在成功ping站点时调用所需的方法。

1

你不跑线程,你只能调用方法。如果方法是instance methods那么你需要一些object;否则它们是static,并且您需要知道它们在其中定义的class。如果你想开始另一个thread,那么你需要一个objectclassimplements Runnable

例如,

try { 
    final URLConnection connection = new URL(url).openConnection(); 
    connection.connect(); 
    } catch (Exception e) { 
    } 
    // connection is available, either use it or close it. then, 

    // AfterConnect is a class that implements Runnable. Perhaps it takes 
    // the connection as parameter? 
    AfterConnect afterConnect = new AfterConnect(..); 

// this will start a new thread 
    new Thread(afterConnect).start(); 

BTW您的例子并不 “等到有连接”。如果您打算让try...catch处于循环状态,则在迭代之间应该有sleep一段时间。

0

我不太清楚你是如何构建“重新运行一些其他类和线程”的东西。如果是在方法调用的混杂,那么你可以把你的抽象类提供的代码,并添加一个抽象方法

abstract class AbstractTimeout { 
    ... your code here, but add a call to afterConnection() ... 

    protected abstract void afterConnection(); 
} 

一个子类,将实现利用所有的类的对象设置一些领域并调用构造函数,然后调用执行的混杂在

protected void afterConnection() { 
    class1.goDoThis(); 
    object2.goDoThat(); 
    someRunnable.run(); 
    // ... etc... 
} 

这是经典inheritance。顺便说一句,你需要考虑什么样的异常可能会被抛出,以及声明哪些异常。为了简单起见,我忽略了这个问题。

另外,如果“重新运行一些其他类和线程”的东西已经在一些相当简单,良好的组织就像一个Runnable,你可以有你的班级采取RunnableURLConnection作为参数一起,并运行()Runnable(或者在新线程中启动它)。这是经典构图。例如

public void doTimeout(URL url, Runnable afterConnection) { 
     // your connection stuff from above 

     afterConnection.run(); 
    } 

注:我没有把afterConnection.run()成线,因为我认为doTimeout应该已经在它自己的线程。因人而异。注2:我的第二种解决方案类似于@Miserable Variable afterConnect()概念。我使用了一个Runnable,他使用了一个更灵活的界面。