Java:使用Array数据启动函数的线程

如何解决Java:使用Array数据启动函数的线程

我对自己做的运动有疑问。

我想创建1,2,4,5,10和20个线程。 First 1 Thread应该单独打开20个网站。网页的内容并不重要。在他完成之后,那么2个线程应该打开相同的20个网站。在那之后的4个线程中,相同的20个网站等等。

这是一个学习如何处理线程的不错的练习。我想停下来想展示一下,线程过多而不是理想选择。

我正在尝试2周,但无法解决。我有一些好主意,但并非100%正确。 下面是一些代码示例:

    import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;

public class ConThread extends Thread{
    
    int name;
    static Integer counter = 0;
    ConcurrentLinkedQueue<String> liste;
    int count2;
    boolean stat = false;
    String data ;

    public ConThread(int name,ConcurrentLinkedQueue<String> liste,Integer counter) {
        this.name = name;
        this.liste = liste;
        //this.counter = counter;
        
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i = 1 ; i < 21 ; i++) {
            synchronized(counter) {
            if(liste.peek()==null) {
                
            } else {
                
                    HttpClient client = HttpClient.newHttpClient();
                    HttpRequest request = HttpRequest.newBuilder()
                            .uri(URI.create(liste.peek()))
                            .build();
    
                    try {
                        HttpResponse<String> response = client.send(request,HttpResponse.BodyHandlers.ofString());
                        System.out.println(liste.size() + " " + getName() + " " + liste.poll());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                    }catch (IndexOutOfBoundsException e) {
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                    }
                    
            }                
                raiseCount();
                
                if(getCount() == 20) {
                    setCount(0);
                }
            }
        }
    }
    
    public void raiseCount() {
        counter=counter+1;
    }
    
    public Integer getCount() {
        return counter;
    }
    
    public void setCount(Integer num) {
        counter= num;
    }

}



import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Main {
    
    public static void main(String args[]) {
        
        
        Integer counter = 0;
        ArrayList<ConThread> threadsList = new ArrayList<>();
        ConcurrentLinkedQueue<String> data = new ConcurrentLinkedQueue<String>();
        ArrayList<Integer> threads = new ArrayList<Integer>();
        threads.add(1);threads.add(2);threads.add(4);threads.add(8);threads.add(10);threads.add(20);
        
        
        
        for(Integer j : threads) {
            
            //******* File reading
            Scanner input = null;
            try {
                //* * * * * * * * * * * * * * * * *
                //---> ADD PATH TO TEXT FILE !!!
                //* * * * * * * * * * * * * * * * * 
                input = new Scanner(new File("/Users/c/Desktop/Aufgabe1_Nachrichtenseiten.txt"));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                System.out.println("Text-file in wrong location!");
                System.out.println("Change directory from text-file or path from scanner.");
            }
            while(input.hasNextLine())
            {
                data.add(input.nextLine());
            }
            input.close();
            threadsList.clear();
        
            System.out.println("* * * * * * * * * * * * Start...");
            //System.out.println();
            long startTime = System.currentTimeMillis();
            
            for (int i = 0; i < j; i++) {
                ConThread t = new ConThread(i,data,counter);
                threadsList.add(t);
                //t.start();
            }
            
            for(ConThread p : threadsList) {
                p.start();
            }
            
            
            
            for (ConThread threadW : threadsList) {
                try {
                    threadW.join();
                    //threadW.interrupt();
                    
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
            threadsList.clear();
            
            long endTime = System.currentTimeMillis();
            long diffTime= endTime - startTime;
            //System.out.println();
            System.out.println("* * * * * * * * * * * * End...");
            System.out.println("* * * * * * * * * * * * Time needed with " + j + " Threads: " + diffTime);
            System.out.println();
            System.out.println();
            
        }
    }
        
        
}

第一个问题是我的线程同步不起作用。 第二个问题是它应该在每个循环之后删除所有线程(threadsList.clear();),并再次从Thread-0开始,但事实并非如此。 第三个问题是在两次循环后,sysout给了我null。所以(像问题一)同步是错误的...

我得到的结果在这里

(图片不起作用,所以这里只有几行...) ...

* * * * * * * * * * * * Start...
20 Thread-7 https://www.spiegel.de/
19 Thread-7 https://www.zeit.de/
18 Thread-14 https://www.nst.com.my
17 Thread-14 https://www.smh.com.au
16 Thread-7 https://www.nzz.ch/
15 Thread-13 https://www.krone.at/
14 Thread-14 https://www.yomiuri.co.jp
13 Thread-7 https://timesofindia.indiatimes.com
12 Thread-12 https://www.nytimes.com
11 Thread-13 https://norwaytoday.info
10 Thread-14 http://www.cankaoxiaoxi.com/
9 Thread-14 https://www.dailymail.com
8 Thread-12 https://www.batimes.com.ar
7 Thread-7 https://news.chosun.com
6 Thread-11 https://www.thairath.co.th/
5 Thread-12 http://english.ahram.org.eg/
4 Thread-7 https://jang.com.pk/
3 Thread-7 https://www.ouest-france.fr/
2 Thread-12 https://www.kp.ru/
1 Thread-12 https://www.telegraaf.nl
0 Thread-11 null
0 Thread-7 null
0 Thread-10 null
0 Thread-14 null
0 Thread-13 null
* * * * * * * * * * * * End...
* * * * * * * * * * * * Time needed with 8 Threads: 5930


* * * * * * * * * * * * Start...
20 Thread-15 https://www.spiegel.de/
19 Thread-24 https://www.zeit.de/
18 Thread-15 https://www.nst.com.my
17 Thread-23 https://www.smh.com.au
16 Thread-24 https://www.nzz.ch/
15 Thread-15 https://www.krone.at/
14 Thread-22 https://www.yomiuri.co.jp
13 Thread-23 https://timesofindia.indiatimes.com
12 Thread-24 https://www.nytimes.com
11 Thread-15 https://norwaytoday.info
10 Thread-23 http://www.cankaoxiaoxi.com/
9 Thread-23 https://www.dailymail.com
8 Thread-21 https://www.batimes.com.ar
7 Thread-22 https://news.chosun.com
6 Thread-20 https://www.thairath.co.th/
5 Thread-22 http://english.ahram.org.eg/
4 Thread-21 https://jang.com.pk/
3 Thread-15 https://www.ouest-france.fr/
2 Thread-22 https://www.kp.ru/
1 Thread-21 https://www.telegraaf.nl
0 Thread-22 null
0 Thread-19 null
0 Thread-20 null
0 Thread-24 null
0 Thread-15 null
0 Thread-23 null
* * * * * * * * * * * * End...
* * * * * * * * * * * * Time needed with 10 Threads: 4078

解决方法

这是我正在使用的代码。我不确定为什么将counter传递给ConThread,但是我将其设置为0。由于计数器是静态的,因此我使用同步静态方法来更改计数器。您可以here来了解它。

这是代码:

ConThread.java

public class ConThread extends Thread {

    int name;
    static Integer counter = 0;
    ConcurrentLinkedQueue<String> urlList;
 
    public ConThread(int name,ConcurrentLinkedQueue<String> urlList) {
        this.name = name;
        this.urlList = urlList;
    }

    @Override
    public void run() {
        while(counter < 20) { //while counter is less than 20,keep polling for new url
           
            try {
                String url = urlList.poll();
                raiseCount();

                //Add your Http request code here
                
                sleep(200);
                System.out.println(getName() + " Thread - " + name + " -- " + url + " --- " + counter);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }
        }
    }

     //Change all methods related to count to synchronized
    public static synchronized void raiseCount() {
        counter=counter+1;
    }

    public static synchronized Integer getCount() {
        return counter;
    }

    public static synchronized void setCount(Integer num) {
        counter= num;
    }

}

Main.java

 public static void main(String args[]) {
        ArrayList<ConThread> threadsList = new ArrayList<>();
        ConcurrentLinkedQueue<String> data = new ConcurrentLinkedQueue<>();
        ArrayList<Integer> threads = new ArrayList<Integer>();
        threads.add(1);
        threads.add(2);
        threads.add(4);
        threads.add(8);
        threads.add(10);
        threads.add(20);

        for (Integer j : threads) {
            //Scan the file to add websites. I am manually adding
            for(int i = 1; i <=20; i++)
                data.add("Url " + String.valueOf(i));


            for (int i = 0; i < j; i++) {
                ConThread t = new ConThread(i,data);
                threadsList.add(t);
            }

            long startTime = System.currentTimeMillis(); //only start the timer before starting the thread
            ConThread.setCount(0); //Set counter to 0

            for (ConThread p : threadsList) {
                p.start();
            }

            for (ConThread threadW : threadsList) {
                try {
                    threadW.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            long endTime = System.currentTimeMillis();
            long diffTime = endTime - startTime;

            threadsList.clear();
            threadsList = new ArrayList<>(); //Setting it as new will clear all values.

            System.out.println("* * * * * * * * * * * * End...");
            System.out.println("* * * * * * * * * * * * Time needed with " + j + " Threads: " + diffTime);
            System.out.println();
            System.out.println();
        }
    }

输出:

Thread-0 Thread - 0 -- Url 1 --- 1
Thread-0 Thread - 0 -- Url 2 --- 2
Thread-0 Thread - 0 -- Url 3 --- 3
Thread-0 Thread - 0 -- Url 4 --- 4
Thread-0 Thread - 0 -- Url 5 --- 5
Thread-0 Thread - 0 -- Url 6 --- 6
Thread-0 Thread - 0 -- Url 7 --- 7
Thread-0 Thread - 0 -- Url 8 --- 8
Thread-0 Thread - 0 -- Url 9 --- 9
Thread-0 Thread - 0 -- Url 10 --- 10
Thread-0 Thread - 0 -- Url 11 --- 11
Thread-0 Thread - 0 -- Url 12 --- 12
Thread-0 Thread - 0 -- Url 13 --- 13
Thread-0 Thread - 0 -- Url 14 --- 14
Thread-0 Thread - 0 -- Url 15 --- 15
Thread-0 Thread - 0 -- Url 16 --- 16
Thread-0 Thread - 0 -- Url 17 --- 17
Thread-0 Thread - 0 -- Url 18 --- 18
Thread-0 Thread - 0 -- Url 19 --- 19
Thread-0 Thread - 0 -- Url 20 --- 20
* * * * * * * * * * * * End...
* * * * * * * * * * * * Time needed with 1 Threads: 4014


Thread-2 Thread - 1 -- Url 2 --- 2
Thread-1 Thread - 0 -- Url 1 --- 2
Thread-1 Thread - 0 -- Url 4 --- 4
Thread-2 Thread - 1 -- Url 3 --- 4
Thread-2 Thread - 1 -- Url 6 --- 6
Thread-1 Thread - 0 -- Url 5 --- 6
Thread-1 Thread - 0 -- Url 8 --- 8
Thread-2 Thread - 1 -- Url 7 --- 8
Thread-2 Thread - 1 -- Url 10 --- 10
Thread-1 Thread - 0 -- Url 9 --- 10
Thread-1 Thread - 0 -- Url 12 --- 12
Thread-2 Thread - 1 -- Url 11 --- 12
Thread-1 Thread - 0 -- Url 13 --- 14
Thread-2 Thread - 1 -- Url 14 --- 14
Thread-1 Thread - 0 -- Url 15 --- 16
Thread-2 Thread - 1 -- Url 16 --- 16
Thread-1 Thread - 0 -- Url 17 --- 18
Thread-2 Thread - 1 -- Url 18 --- 18
Thread-1 Thread - 0 -- Url 19 --- 20
Thread-2 Thread - 1 -- Url 20 --- 20
* * * * * * * * * * * * End...
* * * * * * * * * * * * Time needed with 2 Threads: 2007


Thread-6 Thread - 3 -- Url 4 --- 4
Thread-5 Thread - 2 -- Url 3 --- 4
Thread-3 Thread - 0 -- Url 1 --- 4
Thread-4 Thread - 1 -- Url 2 --- 4
Thread-4 Thread - 1 -- Url 8 --- 8
Thread-6 Thread - 3 -- Url 5 --- 8
Thread-5 Thread - 2 -- Url 6 --- 8
Thread-3 Thread - 0 -- Url 7 --- 8
Thread-4 Thread - 1 -- Url 9 --- 12
Thread-6 Thread - 3 -- Url 10 --- 12
Thread-3 Thread - 0 -- Url 12 --- 12
Thread-5 Thread - 2 -- Url 11 --- 12
Thread-5 Thread - 2 -- Url 16 --- 16
Thread-6 Thread - 3 -- Url 14 --- 16
Thread-3 Thread - 0 -- Url 15 --- 16
Thread-4 Thread - 1 -- Url 13 --- 16
Thread-6 Thread - 3 -- Url 18 --- 20
Thread-5 Thread - 2 -- Url 17 --- 20
Thread-3 Thread - 0 -- Url 19 --- 20
Thread-4 Thread - 1 -- Url 20 --- 20
* * * * * * * * * * * * End...
* * * * * * * * * * * * Time needed with 4 Threads: 1003


Thread-10 Thread - 3 -- Url 4 --- 8
Thread-11 Thread - 4 -- Url 5 --- 8
Thread-7 Thread - 0 -- Url 1 --- 8
Thread-12 Thread - 5 -- Url 8 --- 8
Thread-9 Thread - 2 -- Url 3 --- 8
Thread-13 Thread - 6 -- Url 7 --- 8
Thread-8 Thread - 1 -- Url 2 --- 8
Thread-14 Thread - 7 -- Url 6 --- 8
Thread-12 Thread - 5 -- Url 12 --- 16
Thread-14 Thread - 7 -- Url 16 --- 16
Thread-9 Thread - 2 -- Url 13 --- 16
Thread-11 Thread - 4 -- Url 10 --- 16
Thread-13 Thread - 6 -- Url 14 --- 16
Thread-8 Thread - 1 -- Url 15 --- 16
Thread-10 Thread - 3 -- Url 9 --- 16
Thread-7 Thread - 0 -- Url 11 --- 16
Thread-14 Thread - 7 -- Url 18 --- 20
Thread-11 Thread - 4 -- Url 20 --- 20
Thread-12 Thread - 5 -- Url 17 --- 20
Thread-9 Thread - 2 -- Url 19 --- 20
* * * * * * * * * * * * End...
* * * * * * * * * * * * Time needed with 8 Threads: 605


Thread-15 Thread - 0 -- Url 1 --- 10
Thread-16 Thread - 1 -- Url 2 --- 10
Thread-23 Thread - 8 -- Url 7 --- 12
Thread-17 Thread - 2 -- Url 5 --- 12
Thread-22 Thread - 7 -- Url 6 --- 12
Thread-18 Thread - 3 -- Url 3 --- 12
Thread-19 Thread - 4 -- Url 4 --- 12
Thread-21 Thread - 6 -- Url 9 --- 17
Thread-24 Thread - 9 -- Url 10 --- 17
Thread-20 Thread - 5 -- Url 8 --- 17
Thread-16 Thread - 1 -- Url 12 --- 20
Thread-15 Thread - 0 -- Url 11 --- 20
Thread-17 Thread - 2 -- Url 14 --- 20
Thread-18 Thread - 3 -- Url 16 --- 20
Thread-22 Thread - 7 -- Url 15 --- 20
Thread-23 Thread - 8 -- Url 13 --- 20
Thread-24 Thread - 9 -- Url 19 --- 20
Thread-20 Thread - 5 -- Url 20 --- 20
Thread-19 Thread - 4 -- Url 17 --- 20
Thread-21 Thread - 6 -- Url 18 --- 20
* * * * * * * * * * * * End...
* * * * * * * * * * * * Time needed with 10 Threads: 404


Thread-25 Thread - 0 -- Url 1 --- 20
Thread-31 Thread - 6 -- Url 7 --- 20
Thread-32 Thread - 7 -- Url 8 --- 20
Thread-27 Thread - 2 -- Url 3 --- 20
Thread-28 Thread - 3 -- Url 6 --- 20
Thread-29 Thread - 4 -- Url 5 --- 20
Thread-39 Thread - 14 -- Url 15 --- 20
Thread-30 Thread - 5 -- Url 4 --- 20
Thread-26 Thread - 1 -- Url 2 --- 20
Thread-37 Thread - 12 -- Url 13 --- 20
Thread-36 Thread - 11 -- Url 12 --- 20
Thread-40 Thread - 15 -- Url 14 --- 20
Thread-35 Thread - 10 -- Url 11 --- 20
Thread-34 Thread - 9 -- Url 10 --- 20
Thread-33 Thread - 8 -- Url 9 --- 20
Thread-38 Thread - 13 -- Url 16 --- 20
Thread-43 Thread - 18 -- Url 19 --- 20
Thread-42 Thread - 17 -- Url 18 --- 20
Thread-44 Thread - 19 -- Url 20 --- 20
Thread-41 Thread - 16 -- Url 17 --- 20
* * * * * * * * * * * * End...
* * * * * * * * * * * * Time needed with 20 Threads: 204



Process finished with exit code 0

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res