繁体   English   中英

如何在方法和线程之间共享字符串?

[英]How do you share strings between methods and threads?

我目前正在使用一种方法从剪贴板以字符串形式获取数据,但是我需要从在不同线程上运行的另一种方法访问此信息,我已经做了一些研究并遇到了易失性字符串,但我不太确定如何在我的代码中实现它们,这是我的代码的基础:

public class MobileSite {
public MobileSite(){
Thread thread = new Thread1(() -> {
         try {
             method1();
         } catch (Exception botFailed) {
              System.out.println("Bot Failed");

            }

    });

Thread thread = new Thread2(() -> {
         try {
             method2();
         } catch (Exception botFailed) {
              System.out.println("Bot Failed");

            }

    });


    thread1.start();
    thread2.start();

方法 1 获取数据,方法 2 需要使用字符串格式的数据,如果有人有任何建议,他们将不胜感激

我希望您使用 StringBuilder 而不是使用 String。 下面是工作示例

    StringBuilder txt = new StringBuilder();
public void method1() {
    txt.append("String assigned");      
}

public void method2() {
    System.out.println(txt.toString());
}

public MobileSite(){
    Thread thread1 = new Thread(() -> {
             try {
                 method1();
             } catch (Exception botFailed) {
                  System.out.println("Bot Failed");
                }
        });
    Thread thread2 = new Thread(() -> {
             try {
                 method2();
             } catch (Exception botFailed) {
                  System.out.println("Bot Failed");
                }
        });
        thread1.start();
        thread2.start();

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM