java在线程中定义全局变量,在线程中使用全局变量

How do I share a global variable with thread?

My Python code example is:

from threading import Thread

import time

a = 0 #global variable

def thread1(threadname):

#read variable "a" modify by thread 2

def thread2(threadname):

while 1:

a += 1

time.sleep(1)

thread1 = Thread( target=thread1, args=("Thread-1", ) )

thread2 = Thread( target=thread2, args=("Thread-2", ) )

thread1.join()

thread2.join()

I don't know how to get the two threads to share one variable.

解决方案

You just need to declare a as a global in thread2, so that you aren't modifying an a that is local to that function.

def thread2(threadname):

global a

while True:

a += 1

time.sleep(1)

In thread1, you don't need to do anything special, as long as you don't try to modify the value of a (which would create a local variable that shadows the global one; use global a if you need to)>

def thread1(threadname):

#global a # Optional if you treat a as read-only

while a < 10:

print a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值