java 线程 全局变量,java:是线程中可见的全局变量

本文探讨了在Java中,主线程创建的全局变量如何被新线程访问。指出由于字符串的不变性,可以直接访问但需注意并发修改问题,建议使用volatile关键字确保数据同步。还提到在多线程环境中,如何正确处理局部变量和共享变量的更新。
摘要由CSDN通过智能技术生成

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.*;

/*

*/

public class AppletSkel extends Applet implements Runnable {

String msg = " A Simple Moving Banner."; //<

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

}

}

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值