gpt4 book ai didi

java - 为什么 Clipboard Listener 使用更多 CPU 使用率?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:52:38 24 4
gpt4 key购买 nike

我编写了监听剪贴板的程序并且工作正常,但我发现该程序使用了更多的 CPU。 CPU 使用率超过 70%。为什么?我可以减少它吗?或者我想要监听 Windows 的复制操作的监听器。 Java 中有监听器吗?这是我的代码:

    package yoxlama;


import java.awt.*;
import java.awt.datatransfer.*;
import java.io.IOException;
import java.net.MalformedURLException;

class ClipBoardListener extends Thread implements ClipboardOwner {
Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
static ClipBoardListener b;

Interlsoft interlsoft = new Interlsoft();
public void run() {
try{
Transferable trans = sysClip.getContents(this);
regainOwnership(trans);
}catch (Exception e) {
try {
b.finalize();
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
b= new ClipBoardListener();
b.start();
System.out.println("NESE1");
}
System.out.println("Listening to board...");
while(true) {}
}

public void lostOwnership(Clipboard c, Transferable t) {
try {
Thread.sleep(50);
} catch(Exception e) {
System.out.println("Exception: " + e);
}
try{
Transferable contents = sysClip.getContents(this);
processContents(contents);
regainOwnership(contents);
}catch (Exception e) {
try {
b.finalize();
b= new ClipBoardListener();
b.start();
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("nese");
}
}

void processContents(Transferable t) throws MalformedURLException, IOException {
String str = getClipboard(t);
if(str!=null){
str= str.replace("\n", "%0D%0A");
str= str.replace("\r", "");
str= str.replace("\t", "");
str= str.replace("/", "");
str= str.replace("-", "");
interlsoft.translate(str);

}
// System.out.println("Processing: " + getClipboard(t));

}

void regainOwnership(Transferable t) {
sysClip.setContents(t, this);
}

public static void main(String[] args) {
b = new ClipBoardListener();
b.start();
}

public static String getClipboard(Transferable t) {
// Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);

try {
if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String text = (String)t.getTransferData(DataFlavor.stringFlavor);
return text;
}
} catch (UnsupportedFlavorException e) {
System.out.println("BURDA1");
} catch (IOException e) {
System.out.println("BURDA1");
}
return null;
}
}

最佳答案

这:while(true) {}

你可怜的 CPU。而不是 while true,只是让该线程无限期 hibernate 。请参阅:How do you hang a thread in Java in one line?

关于java - 为什么 Clipboard Listener 使用更多 CPU 使用率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12440177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com