这个是代码:
public class MyThread extends Thread {
static int a=1;
public void run(){
System.out.println(++a);
}
public static void main(String[] args) {
new MyThread().start();
new MyThread().start();
System.out.println("now a is :"+ ++a);
}
}
输出结果是:
2
4
now a is :3但是如果把System.out.println("now a is :"+ ++a);这句和那个static修饰符删掉的话
public class MyThread extends Thread {
int a=1;
public void run(){
System.out.println(++a);
}
public static void main(String[] args) {
new MyThread().start();
new MyThread().start();
}
}
输出结果就变成了:
2
2
public class MyThread extends Thread {
static int a=1;
public void run(){
System.out.println(++a);
}
public static void main(String[] args) {
new MyThread().start();
new MyThread().start();
System.out.println("now a is :"+ ++a);
}
}
输出结果是:
2
4
now a is :3但是如果把System.out.println("now a is :"+ ++a);这句和那个static修饰符删掉的话
public class MyThread extends Thread {
int a=1;
public void run(){
System.out.println(++a);
}
public static void main(String[] args) {
new MyThread().start();
new MyThread().start();
}
}
输出结果就变成了:
2
2
new MyThread().start();//这里也产生了一个对象,每个对象都有属于自己的成员变量,如张三和李四是两个对象,他们都有属于自己的age,name
static int a = 1; public void run() {
try {
sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(++a);
} public static void main(String[] args) {
new MyThread().start(); new MyThread().start();
try {
sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("now a is :" + ++a);
}
}
这个可能是楼主想要的结果吧,额猜的~
其实有两点你要知道就知道为什么第一次输出奇怪的数据
1.static把a修饰成静态变量即大家都用这个a
2.多线程在cpu中其实就就是把线程分成很多个时间块,真正在一个时候运行的只有一个线程的一个时间块,所以我上面这个程序加上sleep()加大MyThread的时间块让你看清楚他们的执行顺序。
3.线程在你调用start方法之后开始启动,
4.关于资源共享问题我还不能说得很清楚(我刚学完javaSE,在练习javaSE的小项目),其中还有关于资源冲突的问题,消费者生产者的问题。建议系统学习线程~
new MyThread().start();
2个线程 如果a有static修饰则a是共享的所有会有线程安全问题.
如果没有static修饰则a是2个线程对象各自的不共享没有线程安全问题。
总结:
非静态成员变量在单列的情况下是共享的有线程安全问题,在单列下建议使用局部变量避免线程安全问题如servlet
静态成员变量不管是不是单列都是共享的