如何在Java中正确使用线程

时间:2019-11-26 16:52:52

标签: java jvm

我有示例线程。我的逻辑是返回路径中的文件数,每3秒更新一次结果并按单词搜索文件。线程应无限运行。我想知道我的代码逻辑是否正确。以及写这样的东西的最佳方法是什么。先感谢您。 我的代码如下:

import java.io.File;
import java.lang.reflect.Field;

public class MyThread implements Runnable {
    private Thread t;
    private String threadName;
    private String word;
    private String path;
    MyThread(String name){
        threadName = name;
        System.out.println(threadName+"thread created");
    }

    @Override
    public void run() {
        System.out.println("Running " +  threadName );
        try {
            File file = new File(path);
            File files[] = file.listFiles();
            System.out.println(files.length);

            if(!word.isEmpty())
            {
                try {

                    for(File f:files){
                        if(f.getName().startsWith(word)){
                            System.out.println(f.getName());
                        }
                    }

                }
                catch (Exception e) {
                    System.err.println(e.getMessage());
                }

            }

        }catch (Exception e) {
            System.out.println("Thread " +  threadName + " interrupted.");
        }

        System.out.println("Thread " +  threadName + " exiting.");
    }

    public void start () {
        System.out.println("Starting " +  threadName );
        if (t == null) {
            t = new Thread (this, threadName);
            t.start ();
        }
    }

    public void setWord(String word){
        this.word = word;
    }

    public void setPath(String path) {
        this.path = path;
    }
}

和Main.java

import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        while (true){
            MyThread first = new MyThread("first");

            Scanner scanner = new Scanner(System.in);
            System.out.println("Enter word :");
            String word = scanner.nextLine();
            first.setWord(word);
            first.setPath("C:\\Users\\myuser\\Desktop");
            first.start();
            Thread.sleep(3000);
        }

    }
}

0 个答案:

没有答案