如何制作彼此的三个类线程

时间:2015-07-09 13:55:01

标签: java database multithreading

我正在构建一个监视文件更改的项目,当文件发生更改时,它会将文件的最后一行作为ID,并在添加ID后将ID上传到数据库,计数器开始某个时间X.下面是我的4个类,它们单独工作但我对如何使用线程感到困惑:

  1. 每个流程完成后,启动下一个流程。
  2. 当整个过程完成后,重新启动该过程并等待文件更改。
  3. 任何帮助都会很棒,如果我的编码很差,我会道歉,对所有这些都是新的!!

    谢谢Jonny

    文件观察者类。

    import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.nio.file.FileSystems;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.WatchEvent;
    import java.nio.file.WatchKey;
    import java.nio.file.WatchService;
    
    public class watcherClock implements Runnable{
    
        static String clkID;
        static boolean done = false;
    
        public static void main(String[] args) throws IOException, InterruptedException {
    
    
            checkFile();
            if(!done){
    
            }
            System.out.println(clkID);
        }
    
        public static String dancerID(){
            return clkID;
    
        }
    
    
        public static void checkFile() {
            try {
                WatchService watcher = FileSystems.getDefault().newWatchService();
                Path dir = Paths.get("/home/jonathan/Desktop/");
                dir.register(watcher, ENTRY_MODIFY);
    
                System.out.println("Watch Service registered for dir: " + dir.getFileName());
    
                while (!done) {
                    WatchKey key;
                    try {
                        key = watcher.take();
                    } catch (InterruptedException ex) {
                        return;
                    }
    
                    for (WatchEvent<?> event : key.pollEvents()) {
                        WatchEvent.Kind<?> kind = event.kind();
    
                        @SuppressWarnings("unchecked")
                        WatchEvent<Path> ev = (WatchEvent<Path>) event;
                        Path fileName = ev.context();
    
                        System.out.println(kind.name() + ": " + fileName);
    
                        if (kind == ENTRY_MODIFY &&
                                fileName.toString().equals("example.txt")) {
                            System.out.println("My source file has changed!!!");
                            String sCurrentLine = null;
                            try (BufferedReader br = new BufferedReader(new FileReader("/home/jonathan/Desktop/example.txt")))
                            {
                                while ((sCurrentLine = br.readLine()) != null) {
                                    System.out.println(sCurrentLine);
                                    clkID = sCurrentLine;
                                    System.out.println(clkID);
                                }
    
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            File inputFile = new File("/home/jonathan/Desktop/example.txt");   // Your file  
                            File tempFile = new File("myTempFile.txt");// temp file
    
                            BufferedReader reader = new BufferedReader(new FileReader(inputFile));
                            BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
    
                            String currentLine;
    
                            while((currentLine = reader.readLine()) != null) {
    
                                        currentLine=("");
                                writer.write(currentLine);
                            }
    
                            writer.close();
                            reader.close();
                            boolean successful = tempFile.renameTo(inputFile);
                            System.out.println(successful);
                            done = true;
                            }
                        }
    
                    boolean valid = key.reset();
                    if (!valid) {
                        break;
                    }
                }
    
            } catch (IOException ex) {
                System.err.println(ex);
            }
        }
    
    
        @Override
        public void run() {
            // TODO Auto-generated method stub
            checkFile();
        }
    
    
    }
    

    计时器的计数器类。

    import java.sql.Timestamp;
    import java.util.Timer;
    import java.util.TimerTask;
    
    public class Counter implements Runnable{
    
       private static TimerTask myTask = null;
    
       public static void main(String[] args) {
          Thread count = new Thread(new Counter());
          count.start();
       }
    @Override
    public void run() {
        // TODO Auto-generated method stub
    }
    
    public static void CounterStart() {
        Timer timer = new Timer("My Timer", false);
      int count = 10;
            System.out.println("LIGHTS ON");
      myTask = new MyTimerTask(count, new Runnable() {
         public void run() {
            System.exit(0);
         }
      });
    
    
      long delay = 1000L;
      timer.scheduleAtFixedRate(myTask, delay, delay);      
    }
    
    }
    
    class MyTimerTask extends TimerTask {
       private int count;
       private Runnable doWhenDone;
    
       public MyTimerTask(int count, Runnable doWhenDone) {
          this.count = count;
          this.doWhenDone = doWhenDone;
       }
    
       @Override
       public void run() {
          count--;
          System.out.println("Count is: " + count);
          if (count == 0) {
              getTimeStamp();
              System.out.println("LIGHTS OFF");
             cancel();
             doWhenDone.run();
          }
       }
    
    
    
      private static void getTimeStamp() {
              java.util.Date date= new java.util.Date();
        System.out.println(new Timestamp(date.getTime()));
      }  
    
    }
    

    数据库连接类

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Calendar;
    
    import com.mysql.jdbc.PreparedStatement;
    import com.mysql.jdbc.StatementImpl;
    
    public class DbConn implements Runnable {
    
    
    
        public static void connection() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                System.out.println("worked");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
        public  void connectionToMySql() {
            watcherClock id = new watcherClock();
            String host ="jdbc:mysql://localhost/test";
            String username ="root";
            String password ="password";
            String dancerID = watcherClock.clkID;
            //System.out.println(dancerID);
            try {
                Connection conn = DriverManager.getConnection(host, username, password);
                System.out.println("Connected:");
                 // the mysql insert statement
                 String query = " insert into dancers (id)"
                   + " values (?)";
    
                 // create the mysql insert preparedstatement
                 PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(query);
                 preparedStmt.setString    (1, dancerID);
                 // execute the preparedstatement
                 preparedStmt.execute();
    
                 conn.close();
    
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                 System.err.println("Got an exception!");
                 System.err.println(e.getMessage());
            }
        }
    
    
        public static void main(String args []){
            Thread thDB = new Thread(new DbConn());
            thDB.start();
            //connection();
        }
    
        @Override
        public void run() {
            // TODO Auto-generated method stub
            connectionToMySql();
        }
    }
    

    最后是我的主要课程

    public class Main implements Runnable{
    
        watcherClock wc = new watcherClock();
        Counter c = new Counter();
    
    
        public static void main(String args[]){
            Thread th1 = new Thread(new watcherClock());
            Thread th3 = new Thread(new Counter());
    
            try {
                th1.start();
                th1.join();
                th3.start();
                th3.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
    
        }
    
    
        @Override
        public void run() {
            // TODO Auto-generated method stub
    
        }
    
    }
    

1 个答案:

答案 0 :(得分:0)

不是答案,但是,这没有任何意义:

th1.start();
th1.join();

它没有任何意义,因为main()线程在th1线程运行的整个时间内什么都不做。

如果你在th1正在做的时候不想做任何其他事情,那为什么还要费心去创建线程呢?为什么不在main()线程中完成工作呢?

th1.run();

拥有线程的全部意义在于,不同的线程可以同时执行不同的事情

th1.start();
doSomethingElseWhileTh1ThreadIsRunning();
th1.join();