黑马程序员技术交流社区
标题:
分享我的面试题
[打印本页]
作者:
huburt
时间:
2016-5-28 10:33
标题:
分享我的面试题
有一个Person类,私有成员属性age,相应的get和set方法。用两个线程对age属性赋值,a线程每次赋age+2的值,b线程不改变age的值,操作10次。
public class Test1 {
static int times = 1;
public static void main(String[] args) {
Person p = new Person(50);
new Thread() {
public void run() {
method(p, 2);
};
}.start();
new Thread() {
public void run() {
method(p, 0);
};
}.start();
System.out.println(p.getWeight());
}
public static void method(Person p, int i) {
while (true) {
synchronized (Test1.class) {
if (times >= 10) {
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
p.setWeight(p.getWeight() + i);
System.out.println(p.getWeight());
times++;
}
}
}
}
class Person {
private int weight;
public Person(int weight) {
super();
this.weight = weight;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
复制代码
作者:
sishuidliunian
时间:
2016-5-28 11:15
while (true) 也能使用for循环吧
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2