如何使用java

时间:2016-03-16 20:41:28

标签: java multithreading runnable

我正在尝试创建一个程序,它将继续自动运行,而无需我做任何事情。我对如何在java中实现runnable感到有点困惑所以我可以创建一个线程,它将在一段时间内进入休眠状态,然后在睡眠期结束后重新运行程序。

public class work {

public static void main(String[] args) throws IOException, InterruptedException {

    work test = new work();
    test.information();

}

private ConfigurationBuilder OAuthBuilder() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey("dy1Vcv3iGYTqFif6m4oYpGBhq");
    cb.setOAuthConsumerSecret("wKKJ1XOPZbxX0hywDycDcZf40qxfHvkDXYdINWYXGUH04qU0ha");
    cb.setOAuthAccessToken("4850486261-49Eqv5mogjooJr8lm86hB20QRUpxeHq5iIzBLks");
    cb.setOAuthAccessTokenSecret("QLeIKTTxJOwpSX4zEasREtGcXcqr0mY8wk5hRZKYrH5pd");
    return cb; 



}

public void information() throws IOException, InterruptedException {

    ConfigurationBuilder cb = OAuthBuilder();
    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
    try {
        User user = twitter.showUser("ec12327");
        Query query = new Query("gym fanatic");
        query.setCount(100);
        query.lang("en");
        String rawJSON =null ;
        String statusfile = null;
        int i=0;

    try {     

                QueryResult result = twitter.search(query);
                for(int z = 0;z<5;z++){
                for( Status status : result.getTweets()){

                    System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());

                       rawJSON = TwitterObjectFactory.getRawJSON(status);
                         statusfile = "results" + z +".txt";
                        storeJSON(rawJSON, statusfile);

                        i++;

                }
    }


                System.out.println(i);

              }   
              catch(TwitterException e) {         
                System.out.println("Get timeline: " + e + " Status code: " + e.getStatusCode());
                if(e.getErrorCode() == 88){
                    Thread.sleep(900);
                    information();

                }
              }     


    } catch (TwitterException e) {
        if (e.getErrorCode() == 88) {
            System.err.println("Rate Limit exceeded!!!!!!");
            Thread.sleep(90);
            information();
            try {
                long time = e.getRateLimitStatus().getSecondsUntilReset();
                if (time > 0)
                    Thread.sleep(900000);
                    information();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
    }
}

 private static void storeJSON(String rawJSON, String fileName) throws IOException {
        FileWriter fileWriter = null;
        try
        {
            fileWriter = new FileWriter(fileName, true);
            fileWriter.write(rawJSON);
            fileWriter.write("\n");
        }
        catch(IOException ioe)
        {
            System.err.println("IOException: " + ioe.getMessage());
        } finally {
            if(fileWriter!=null) {
                fileWriter.close();
            }
        }
    }

}

3 个答案:

答案 0 :(得分:0)

你有可分离的选项来用Java实现一个线程。

实施Runnable

当一个类实现Runnable接口时,他必须覆盖run()方法。可以将此runnable传递给Thread的构造函数。然后可以使用start()方法执行此线程。如果您想让这个线程永远运行并且睡眠,您可以执行以下操作:

public class HelloRunnable implements Runnable {
    public void run() {
        while(true){
            Thread.sleep(1000);
            System.out.println("Hello from a thread!");
        }
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }
}

扩展Thread

线程本身也有run()方法。扩展线程时,您可以覆盖Thread的run()方法并提供自己的实现。然后,您必须实例化自己的自定义线程,并以相同的方式启动它。再次,像以前一样,你可以这样做:

public class HelloThread extends Thread {
    public void run() {
        while(true){
            Thread.sleep(1000);
            System.out.println("Hello from a thread!");
        }
    }

    public static void main(String args[]) {
        (new HelloThread()).start();
    }
}

来源:Oracle documentation

答案 1 :(得分:0)

在前一个答案的基础上,您需要在Work类上扩展Thread或实现Runnable。扩展线程可能更容易。

public class work extends Thread {

    public void run() {
        // your app will run forever, consider a break mechanism
        while(true) {
            // sleep for a while, otherwise you'll max your CPU
            Thread.sleep( 1000 );
            this.information();
        }
    }

    public static void main(String[] args) throws IOException,    InterruptedException {
        work test = new work();
        test.start();
   }

    // ... rest of your class
 }

答案 2 :(得分:0)

public static void main(String[] args){
    Thread thread = new Thread(runnable); // create new thread instance
    thread.start(); // start thread
}


public static Runnable runnable = new Runnable(){
    @Override
    public void run(){

      final int DELAY = 500;
      while(true){
          try{
               // Code goes here;
               Thread.sleep(DELAY)
          } catch(Exception e){
              e.printStackTrace();                    
          }

      }

   }

}