java黑马面试_java基础,黑马面试笔试题

无详细内容 无 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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值