无详细内容 无 package com.itheima2;/* * 定义一个Person类,属性有weight(为int类型,初始值为50),生成set/get方法, * 创建一个Person对象(后面创建的两个线程都来操作这个数据),创建两个线程(A和B), * 每当A线程执行时,通过set方法将weight增加

package com.itheima2;

/*

* 定义一个Person类,属性有weight(为int类型,初始值为50),生成set/get方法,

* 创建一个Person对象(后面创建的两个线程都来操作这个数据),创建两个线程(A和B),

* 每当A线程执行时,通过set方法将weight增加2,B线程执行时,不做改变(什么都不做),无论哪条线程执行,

* 总共只能执行10次

* 第一种方法:线程与线程执行目标类分离的方式创建线程对象,开启线程

* 第二种方法:

* */

public class Test2 {

static int number = 1;

static Person p = new Person();

public static void main(String[] args) {

Thread thread = new Thread(new Runnable(){

int weight = p.getWeight();

@Override

public void run() {

while(number<=10){

synchronized (this) {

weight = weight+2;

System.out.println("线程A执行第"+number+++"次"+weight);

}

}

}

});

Thread thread2 = new Thread(new Runnable(){

int weight = p.getWeight();

@Override

public void run() {

while(number<=10){

synchronized (this) {

System.out.println("线程B执行第"+number+++"次"+weight);

}

}

}

});

thread.start();

thread2.start();

}

package com.itheima2;

public class Person {

private int weight = 50;

// ======GS=======

public int getWeight() {

return weight;

}

public void setWeight(int weight) {

this.weight = weight;

}

}

}

package com.itheima2;

/*

* 定义一个Person类,属性有weight(为int类型,初始值为50),生成set/get方法,

* 创建一个Person对象(后面创建的两个线程都来操作这个数据),创建两个线程(A和B),

* 每当A线程执行时,通过set方法将weight增加2,B线程执行时,不做改变(什么都不做),无论哪条线程执行,

* 总共只能执行10次

* 第一种方法:线程与线程执行目标类分离的方式创建线程对象,开启线程

* 第二种方法:

* */

public class Test2 {

static int number = 1;

static Person p = new Person();

public static void main(String[] args) {

Thread thread = new Thread(new Runnable(){

int weight = p.getWeight();

@Override

public void run() {

while(number<=10){

synchronized (this) {

weight = weight+2;

System.out.println("线程A执行第"+number+++"次"+weight);

}

}

}

});

Thread thread2 = new Thread(new Runnable(){

int weight = p.getWeight();

@Override

public void run() {

while(number<=10){

synchronized (this) {

System.out.println("线程B执行第"+number+++"次"+weight);

}

}

}

});

thread.start();

thread2.start();

}

}

public class Person {

private int weight = 50;

// ======GS=======

public int getWeight() {

return weight;

}

public void setWeight(int weight) {

this.weight = weight;

}

}

更多推荐