简体   繁体   English

如何使用Java实现可运行

[英]How to implement runnable with java

I am trying to create a program that will carry on running automatically without me having to do anything. 我正在尝试创建一个程序,该程序可以自动运行,而无需执行任何操作。 I am a bit confused on how to implement runnable in java so I can create a thread that will go to sleep for a certain period of time and then run the re-run the program after the sleep period is over. 我对如何在Java中实现可运行性感到有些困惑,因此我可以创建一个将在特定时间段内进入睡眠状态的线程,然后在睡眠时间结束后运行重新运行程序。

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();
            }
        }
    }

} }

You have severable options to implement a thread in Java. 您具有可分割的选项来用Java实现线程。

Implementing Runnable 实现Runnable

When a class implements the Runnable interface, he has to override the run() method. 当一个类实现Runnable接口时,他必须重写run()方法。 This runnable can be passed to the constructor of a Thread . 该可运行对象可以传递给Thread的构造函数。 This thread can then be executed using the start() method. 然后可以使用start()方法执行此线程。 If you'd like to have this thread run forever and sleep, you could do something like the following: 如果您希望此线程永久运行并进入睡眠状态,则可以执行以下操作:

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();
    }
}

Extending Thread 延伸Thread

Thread itself also has a run() method. 线程本身也具有run()方法。 When extending thread, you can override the Thread's run() method and provide your own implementation. 扩展线程时,可以重写Thread的run()方法并提供自己的实现。 Then you'd have to instantiate your own custom thread, and start it in the same way. 然后,您必须实例化自己的自定义线程,并以相同的方式启动它。 Again, like the previous you could do this: 再次,像以前一样,您可以执行以下操作:

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();
    }
}

Source: Oracle documentation 资料来源: Oracle文档

Building on the previous answer, you need to either extend Thread or implement Runnable on your Work class. 在上一个答案的基础上,您需要扩展Thread或在Work类上实现Runnable。 Extending Thread is probably easier. 扩展线程可能更容易。

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
 }
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();                    
          }

      }

   }

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM