如果是一个相同对象在多线程中,数据是成员变量 共享count 局部变量不共享 a
看下面的例子:
class Demo implements Runnable
{
int count=0;
public void show()
{
int a=0;
a=a+10;
System.out.println("show:"+a);
}
@Override
public void run() {
count=count+3;
System.out.println(count);
show();
}
}
public class Demo1
{
public static void main(String[] args) throws InterruptedException {
Demo d= new Demo();
Thread S1=new Thread(d);
S1.start();
Thread.sleep(1000);
Thread S2=new Thread(d);
S2.start();
}
}
此时开了两个线程: S1 ,S2 他们是同一个对象 d
返回结果:
3
show:10
6
show:10
如果改下: 用不同的对象d1 和 d2
class Demo implements Runnable
{
int count=0;
public void show()
{
int a=0;
a=a+10;
System.out.println("show:"+a);
}
@Override
public void run() {
count=count+3;
System.out.println(count);
show();
}
}
public class Demo1
{
public static void main(String[] args) throws InterruptedException {
Demo d1= new Demo();
Demo d2= new Demo();
Thread S1=new Thread(d1);
S1.start();
Thread.sleep(1000);
Thread S2=new Thread(d2);
S2.start();
}
}
此时成员变量 count 和局部变量a 都不共享
3
show:10
3
show:10
d1和d2要在多线程中共享count此时要修改代码如下:
count 加 static 关键字
class Demo implements Runnable
{
static int count=0;
public void show()
{
int a=0;
a=a+10;
System.out.println("show:"+a);
}
@Override
public void run() {
count=count+3;
System.out.println(count);
show();
}
}
public class Demo1
{
public static void main(String[] args) throws InterruptedException {
Demo d1= new Demo();
Demo d2= new Demo();
Thread S1=new Thread(d1);
S1.start();
Thread.sleep(1000);
Thread S2=new Thread(d2);
S2.start();
}
}
运行结果:
3
show:10
6
show:10