gpt4 book ai didi

java - 多线程和队列

转载 作者:行者123 更新时间:2023-11-29 05:05:45 25 4
gpt4 key购买 nike

我有点掌握线程的窍门,但现在我很困惑。我不太了解队列。我创建了一个线程池执行器,它初始化一定数量的线程,每个线程在网站上输入用户名(字符串)以检查其是否可用。所以基本上我在想我应该排队吗?像 queue.add(username) 和 queue.remove(username) 或 queue.take.. 所以我想知道如何用线程池和哪种类型做队列。 SynchronousQueue、BlockingQueue,或者有更好的选择吗?对不起,我真的不懂排队。忽略错误代码。只是希望它在我联网之前工作

FilterUsers FU = new FilterUsers();
HtmlThread[] threads = new HtmlThread[users.length];
ExecutorService executor = Executors.newFixedThreadPool(threadNo);
for (int i = 0; i < users.length; i++) {
Runnable worker = new HtmlThread(" "+i, FU, users[i]);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()){ }

这是 HtmlThread 类

class HtmlThread extends Thread {
private Thread t;
private String threadName;
FilterUsers filterUsers;
String users;

public HtmlThread(String tName, FilterUsers filterusers, String user) {
this.threadName = tName;
this.filterUsers = filterusers;
this.users = user;
}

public void run() {
synchronized (filterUsers) {
try {
HtmlPage page = webClient.getPage("https://website.com/account/edit");

try {
final HtmlForm form = page.getFirstByXPath("//form[@class='adjacent bordered']");
HtmlTextInput user = form.getInputByName("username");
HtmlSubmitInput b = form.getInputByValue("Submit");
user.setValueAttribute(users);

HtmlPage page2;
page2 = b.click();

String html = page2.getWebResponse().getContentAsString();
if (page2 != null) {
if (!html.contains("that username is taken")) {
Filter.validUsers.appendText(users + "\n");
}
}
} finally {
page.cleanUp();
}
} catch (Exception e) {
e.printStackTrace();
}
}
try {
System.out.println("Thread " + threadName + " Sleeping.");

Thread.sleep(3500);
} catch (InterruptedException e) {
e.printStackTrace();
}

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

最佳答案

哦,您担心返回结果。根据您的评论:

I updated with code. When I do this it goes way too fast. even though I put thread to sleep for 3.5 secs. I dont think it actually sleeps. So I thought I should add queue to prevent loss of data or w/e

好吧,你应该在你的问题中这么说。您可以使用队列,但 Java 实际上有它自己的数据返回机制。您至少应该先尝试一下。

要返回结果,请使用 Callable 接口(interface)而不是 Thread/Runnable。 Callable 的工作方式与 Runnable 类似,只是您可以返回一个值。当您将 Callable 提交给执行程序服务时,您会得到一个 Future 返回。只需保存它,然后调用 get() 即可获得结果。就是这样,制作队列或同步的所有艰苦工作都已经为您完成。

剩下的唯一事情就是在几乎所有可以想象到的地方检查 InterruptedException。 ;)

/**
*
* @author Brenden Towey
*/
public class FutureExample
{

public static void main( String[] args )
{
ExecutorService exe = Executors.newFixedThreadPool(3);
List<Future<String>> results = new ArrayList<>();
for( int i = 0; i < 5; i++ )
results.add( exe.submit( new HtmlTask() ) );
try {
for( Future<String> future : results )
System.out.println( future.get() );
} catch( InterruptedException x ) {
// bail
} catch( ExecutionException ex ) {
Logger.getLogger( FutureExample.class.getName() ).
log( Level.SEVERE, null, ex );
// and bail
}
exe.shutdown();
boolean shutdown = false;
try {
shutdown = exe.awaitTermination(10 , TimeUnit.SECONDS );
} catch( InterruptedException ex ) {
// bail
}
if( !shutdown ) {
exe.shutdownNow();
try {
exe.awaitTermination( 30, TimeUnit.SECONDS );
} catch( InterruptedException ex ) {
// just exit
}
}
}
}

class HtmlTask implements Callable<String> {

@Override
public String call()
throws Exception
{
// pretend to search a website and return some result
return "200 OK";
}

}

关于java - 多线程和队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30416336/

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