有一个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;
- }
- }
复制代码 |
|