2

if I declare a global variable in the main thread, suppose that from the main thread I run a new thread, can the new thread access the global variable in the main thread?

"msg" string is my variable to acces

/* A simple banner applet.

   This applet creates a thread that scrolls
   the message contained in msg right to left
   across the applet's window.
*/
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleBanner" width=300 height=50>
</applet>
*/

public class AppletSkel extends Applet implements Runnable {
  String msg = " A Simple Moving Banner.";  //<<-----------------VARIABLE TO ACCESS
  Thread t = null;
  int state;
  boolean stopFlag;

  // Set colors and initialize thread.
  public void init() {
    setBackground(Color.cyan);
    setForeground(Color.red);
  }

  // Start thread
  public void start() {
    t = new Thread(this);
    stopFlag = false;
    t.start();
  }

  // Entry point for the thread that runs the banner.
  public void run() {
    char ch;

    // Display banner 
    for( ; ; ) {
      try {
        repaint();
        Thread.sleep(250);
        ch = msg.charAt(0);
        msg = msg.substring(1, msg.length());
        msg += ch;
        if(stopFlag)
          break;
      } catch(InterruptedException e) {}
    }
  }

  // Pause the banner.
  public void stop() {
    stopFlag = true;
    t = null;
  }

  // Display the banner.
  public void paint(Graphics g) {
    g.drawString(msg, 50, 30);
    g.drawString(msg, 80, 40);
  }
}
6
  • 3
    What do you mean by global variable? public static? Then yes, so careful when modifying it. Commented Jul 25, 2013 at 17:51
  • Yes. That's why you have to worry about thread-safety. Commented Jul 25, 2013 at 17:52
  • A small code fragment would help to understand what you are asking. Commented Jul 25, 2013 at 17:52
  • what if the varible in the main thread is just public and not static? Commented Jul 25, 2013 at 17:53
  • 1
    @Luther Then your other thread would have to have a reference to the object that contains the variable. Commented Jul 25, 2013 at 17:55

1 Answer 1

5

Variables that are visible to several threads are generally tricky. Strings, however, are immutable, so that simplifies the situation.

It is visible, but when a modified ordinary value is available to other threads is not guaranteed. You should make it volatile, so that it is not cached thread locally. Use a local variable to build the new string before assigning msg.

If you intend to modify stopFlag from other threads, it should also be volatile.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.