简体   繁体   中英

How do you share strings between methods and threads?

I'm currently getting data from my clipboard in string form using one method however I need to access this information from another method running on a different thread, I've done some research and come across volatile strings but I am not quite sure how to implement them in my code, this is the basics of my code:

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();

method 1 gets the data and method 2 needs to use that data being in string format if anyone has any suggestions they would be much appreciated

I would prefer you to use StringBuilder instead of using String. Below is working example

    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();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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