【问题标题】:How to implement runnable with java如何用java实现runnable
【发布时间】:2016-07-02 23:21:05
【问题描述】:

我正在尝试创建一个程序,该程序将自动运行而无需我做任何事情。我对如何在 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();
            }
        }
    }

}

【问题讨论】:

    标签: java multithreading runnable


    【解决方案1】:

    在 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() 方法。扩展线程时,您可以覆盖线程的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

    【讨论】:

    • 我将如何用初始代码实现它,我有点困惑它是如何工作的
    • @shah 那么您希望看到哪些代码连续运行?如果您有需要连续运行的逻辑,请创建一个类,实现Runnable 接口并在run() 方法中定义您的逻辑。然后,创建一个线程并传入实现该接口的类。然后在线程上调用start()
    • 我希望能够运行 for 循环以使其保持打印结果,然后停止 x 秒,然后再次运行 for 循环以打印更多结果。
    【解决方案2】:

    在上一个答案的基础上,您需要扩展 Thread 或在 Work 类上实现 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
     }
    

    【讨论】:

      【解决方案3】:
      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();                    
                }
      
            }
      
         }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-05
        相关资源
        最近更新 更多