Java 多线程大写字符串

我有一个字符串:“abcdef”和 3 个线程:t1、t2 和 t3。我希望他们返回大写的字符串:“ABCDEF”(字符顺序无关紧要)。我设法将字符串大写 3 次。我希望这一切只发生一次。这是主类:


public static void main(String[] args) {

    Thread t1 = new Thread(new CapitalizeString("Thread 1", "abcdef"));

    Thread t2 = new Thread(new CapitalizeString("Thread 2", "abcdef"));

    Thread t3 = new Thread(new CapitalizeString("Thread 3", "abcdef"));


    t1.start();

    t2.start();

    t3.start();


}

这是用于大写的类:


import java.util.Random;


public class CapitalizeString implements Runnable {

String list;

String nameThread;


public CapitalizeString(String name, String str) {

    nameThread = name;

    list = str;

}


public void capitalize() {

    char[] arr = list.toCharArray();


    for (int i = 0; i < list.length(); i++) {

        arr[i] = Character.toUpperCase(arr[i]);

        System.out.println("Thread-ul " + nameThread + " solved " + arr[i]);

    }

    System.out.print("\n");

}


@Override

public void run() {

    try {

        capitalize();

    } catch (Exception e) {

    }

}

}



慕勒3428872
浏览 121回答 3
3回答

沧海一幻觉

这不仅会复杂得多,而且会慢很多倍。但是,作为练习,我建议使用最简单的方法,即使用 parallelStreamString upper = "abcdef".chars().parallel()&nbsp; &nbsp; &nbsp; &nbsp; .map(Character::toUpperCase)&nbsp; &nbsp; &nbsp; &nbsp; .mapToObj(c -> Character.toString((char) c))&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.joining());System.out.println(upper);你可能想知道,为什么这么慢?从人的尺度考虑这个,你可以a) 在纸上手工转换字母,或b) 你可以给三个朋友寄三封信,让他们每人给你寄两封大写的信。除了更糟糕的是,因为必须首先启动线程,这需要更长的时间,所以真的是这样c) 找三个愿意回信的新朋友然后 b)

当年话下

注意:String str = "abcdef".toUpperCase();对于短字符串,仅使用要快得多(在我的计算机上,当字符串长度约为 50000 个字符时,多线程代码开始工作得更快)。该字符串被拆分为一个字符数组 ( chars)。每个线程遍历数组chars,将一个字母转换为大写,并跳过两个字母供其他线程处理。当所有线程都完成后,数组将变回String.public static void main(String args[]) {&nbsp; &nbsp; String str = "abcdef";&nbsp; &nbsp; System.out.println(str);&nbsp; &nbsp; char[] chars = str.toCharArray();&nbsp; &nbsp; Thread t1 = new Thread(new CapitalizeString(chars, 0, 3));&nbsp; &nbsp; Thread t2 = new Thread(new CapitalizeString(chars, 1, 3));&nbsp; &nbsp; Thread t3 = new Thread(new CapitalizeString(chars, 2, 3));&nbsp; &nbsp; t1.start();&nbsp; &nbsp; t2.start();&nbsp; &nbsp; t3.start();&nbsp; &nbsp; // wait until all threads finish their work&nbsp; &nbsp; try{&nbsp; &nbsp; &nbsp; &nbsp; t1.join();&nbsp; &nbsp; &nbsp; &nbsp; t2.join();&nbsp; &nbsp; &nbsp; &nbsp; t3.join();&nbsp; &nbsp; }catch(InterruptedException e){ }&nbsp; &nbsp; // print the result&nbsp; &nbsp; str = String.valueOf(chars);&nbsp; &nbsp; System.out.println(str);}类大写字符串:public class CapitalizeString implements Runnable {&nbsp; &nbsp; char[] chars;&nbsp; &nbsp; int start;&nbsp; &nbsp; int numThreads;&nbsp; &nbsp; public CapitalizeString(char[] chars, int startIndex, int numThreads) {&nbsp; &nbsp; &nbsp; &nbsp; this.chars = chars;&nbsp; &nbsp; &nbsp; &nbsp; this.numThreads = numThreads;&nbsp; &nbsp; &nbsp; &nbsp; start = startIndex;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; for(int x = start; x < chars.length; x += numThreads){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; chars[x] = Character.toUpperCase(chars[x]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

慕婉清6462132

是的,问题在我第一次回复后被修改,现在有一个可以接受的答案,但我还是想发表评论。这可能被认为是一个更完整的示例,因为CapitalizeWorker线程正在从CapitalizeJob类中获取工作并将结果返回。我认为这是一个更好的例子,因为它不依赖于特定数量的线程,而是针对您的系统拥有的核心数量进行了优化。它也在以干净的方式关闭并等待结果。只是我价值 0.02 美元。private void run() throws InterruptedException {&nbsp; &nbsp; CapitalizeJob capitalizeJob = new CapitalizeJob("abcdef");&nbsp; &nbsp; int processors = Runtime.getRuntime().availableProcessors();&nbsp; &nbsp; ExecutorService executors = Executors.newFixedThreadPool(processors);&nbsp; &nbsp; for ( int t = 0; t < processors; ++t) {&nbsp; &nbsp; &nbsp; &nbsp; executors.execute(new CapitalizeWorker(capitalizeJob));&nbsp; &nbsp; }&nbsp; &nbsp; executors.shutdown(); // this is missing from OP thread example&nbsp; &nbsp; executors.awaitTermination(10, TimeUnit.SECONDS);&nbsp; &nbsp; System.out.println( capitalizeJob.getResult() );}public class CapitalizeWorker implements Runnable {&nbsp; &nbsp; private CapitalizeJob capitalizeJob;&nbsp; &nbsp; CapitalizeWorker(CapitalizeJob capitalizeJob) {&nbsp; &nbsp; &nbsp; &nbsp; this.capitalizeJob = capitalizeJob;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; char c;&nbsp; &nbsp; &nbsp; &nbsp; while ( (c = capitalizeJob.getNextChar()) != 0 ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(Thread.currentThread().toString());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; capitalizeJob.setNextChar(Character.toUpperCase(c));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}public class CapitalizeJob {&nbsp; &nbsp; private char[] arr;&nbsp; &nbsp; private int jobIndex;&nbsp; &nbsp; private char[] result;&nbsp; &nbsp; private int resultIndex;&nbsp; &nbsp; public CapitalizeJob(String name) {&nbsp; &nbsp; &nbsp; &nbsp; arr = name.toCharArray();&nbsp; &nbsp; &nbsp; &nbsp; result = new char[arr.length];&nbsp; &nbsp; &nbsp; &nbsp; jobIndex = 0;&nbsp; &nbsp; &nbsp; &nbsp; resultIndex = 0;&nbsp; &nbsp; }&nbsp; &nbsp; public synchronized char getNextChar() {&nbsp; &nbsp; &nbsp; &nbsp; return jobIndex < arr.length ? arr[jobIndex++] : 0 ;&nbsp; &nbsp; }&nbsp; &nbsp; public synchronized void setNextChar(char c) {&nbsp; &nbsp; &nbsp; &nbsp; result[resultIndex++] = c;&nbsp; &nbsp; }&nbsp; &nbsp; public String getResult() {&nbsp; &nbsp; &nbsp; &nbsp; return new String(result);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java