gpt4 book ai didi

Java多线程 - 如何制作线程序列?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:03:53 25 4
gpt4 key购买 nike

<分区>

public class wshop8 {
public static void main(String[] args) {
SearchThread[] threads = new SearchThread[5];

String[][] s = {
{ "java", "I love java", "c++", "python" },
{ "c programs", "cookies", "java developers", "oops"},
{ "john", "doe", "mary", "mark holmes"},
{ "hello java java", "byebye", "java again?", "what?"},
{ "toronto", "montreal", "quebec city", "calgary"}
};

for(int i=0;i<threads.length;i++){
threads[i] = new SearchThread( s[i] ); //Insert each line of String s into threads array
threads[i].start(); //Threads begin...
}
for(int i=0;i<threads.length;i++){
try{
threads[i].join();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
}

class SearchThread extends Thread{
private String[] search;

public SearchThread(String[] search){this.search = search;}

public synchronized void run(){
for(int i=0;i<search.length;i++){
System.out.print(search[i]+" ");
}
System.out.println();
}
}

嗨。上面是我现在做的代码..

每次我编译程序时,它都会给我随机的输出序列。

我认为线程正在互相拦截。

有什么技巧可以让程序输出从 s[0] 到 s[4] 的字符串吗?

我也试过设置优先级,但我失败了。


下面是我也试过的另一个版本。 (不使用 obj 线程的数组)而且也是随机输出。

public class wshop8 {
public static void main(String[] args) {
SearchThread thread;

String[][] s = {
{ "java", "I love java", "c++", "python" },
{ "c programs", "cookies", "java developers", "oops"},
{ "john", "doe", "mary", "mark holmes"},
{ "hello java java", "byebye", "java again?", "what?"},
{ "toronto", "montreal", "quebec city", "calgary"}
};

for(int i=0;i<5;i++){
thread = new SearchThread( s[i] ); //Insert each line of String s into threads array
thread.start(); //Threads begin...
}
}
}

class SearchThread extends Thread{
private String[] search;

public SearchThread(String[] search){this.search = search;}

//override
public synchronized void run(){

for(int i=0;i<search.length;i++){
System.out.print(search[i]+" ");
}
System.out.println();
}
}

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