[英]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.