java - 如何使三个类线程相互关联

标签 java database multithreading

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

  1. 每个流程完成后,开始下一个流程。
  2. 整个过程完成后,再次重新启动该过程并等待文件更改。

任何帮助都会很棒,如果我的编码很差,我深表歉意,我对这一切都很陌生!!

谢谢乔尼

文件观察器类。

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

    }

}

最佳答案

这并不是一个真正的答案,但是,这没有任何意义:

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

这没有任何意义,因为 main() 线程在 th1 线程运行的整个时间内根本不执行任何操作。

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

th1.run();

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

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

关于java - 如何使三个类线程相互关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31319665/

相关文章:

.net - 从 Umbraco (4.7) 数据库获取节点 URl

sql - 按 DISTINCT 列限制/偏移

c++ - 测试等待队列中 condition_variables 的多个线程

java - @Transactional测试中未填充联接表

java - 按下按钮时无法显示 JOptionPane

java - 如何在 Opennlp 中训练 Chunker?

java - 并发 - 以线程安全的方式获取通过 Java 插入的对象的 MongoDB 生成 ID

database - 如何将数据库上传到 Heroku

c# - 线程池中排队的任务正在退出,不会被释放回池中

java - 如何向 Java 线程传递参数?