Java栈:线程私有,用于存放局部变量,方法参数,同时和java方法的调用返回密切相关。
栈上分配的基本思想,是将线程私有的对象,打散分配到栈上,分配在栈上的函数调用结束后对象会自行销毁,不需要垃圾回收接入:方法内部变量线程安全
public class Text {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
HasSelfPrivateNum num = new HasSelfPrivateNum();
ThreadA a = new ThreadA(num);
ThreadB b = new ThreadB(num);
a.start();
b.start();
}
}
public class HasSelfPrivateNum {
public void addI(String username) {
int num;
if (username.equals("a")) {
num = 100;
System.out.println("a set over");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
num = 200;
System.out.println("b set over");
}
System.out.println(username + "num = " + num);
}
}
public class ThreadA extends Thread {
public HasSelfPrivateNum num;
public ThreadA(HasSelfPrivateNum num) {
// TODO Auto-generated constructor stub
this.num = num;
}
public void run() {
// TODO Auto-generated method stub
num.addI("a");
}
}
public class ThreadB extends Thread{
private HasSelfPrivateNum num;
public ThreadB(HasSelfPrivateNum num) {
// TODO Auto-generated constructor stub
this.num = num;
}
public void run() {
// TODO Auto-generated method stub
num.addI("b");
}
}