首页 > 编程语言 > 详细

Java多线程--两个线程同时对一个人的年龄进行增加和修改

时间:2020-07-27 23:50:05      阅读:73      评论:0      收藏:0      [点我收藏+]
 1 public class Thread_A extends Thread {
 2     Human human;
 3 
 4     public Thread_A(String name, Human human) {
 5         super(name);
 6         this.human = human;
 7     }
 8 
 9     @Override
10     public void run() {
11         for (int i = 0; i < 100; i++) {
12             human.setAge(human.getAge()+1);
13             System.out.println(getName()+"线程实现Human的年龄+1,当前年龄:"+human.getAge());
14         }
15 
16     }
17 }
 1 public class Thread_B extends Thread {
 2     Human human;
 3 
 4     public Thread_B(String name,Human human) {
 5         super(name);
 6         this.human = human;
 7     }
 8 
 9     @Override
10     public void run() {
11         for (int i = 0; i < 100; i++) {
12             human.setAge(human.getAge()-1);
13             System.out.println(getName()+"线程实现Human的年龄-1,当前年龄:"+human.getAge());
14         }
15     }
16 }
1 public class TestThread {
2     public static void main(String[] args) {
3         Human human = new Human("张三", 10);
4         Thread t1 = new Thread(new Thread_A("A",human));
5         Thread t2 = new Thread(new Thread_B("B",human));
6         t1.start();
7         t2.start();
8     }
9 }
 1 @SuppressWarnings("all")
 2 public class Human {
 3     private String name;
 4     private int age;
 5 
 6     public Human() {
 7     }
 8 
 9     public Human(String name, int age) {
10         this.name = name;
11         this.age = age;
12     }
13 
14     public int getAge() {
15         return age;
16     }
17 
18     public synchronized void setAge(int age) {
19         if (age>0){
20             this.age = age;
21         }else {
22             this.age = 0;
23         }
24     }
25 
26     @Override
27     public String toString() {
28         return "Human{" +
29                 "name=‘" + name + ‘\‘‘ +
30                 ", age=" + age +
31                 ‘}‘;
32     }
33 }

技术分享图片

 

Java多线程--两个线程同时对一个人的年龄进行增加和修改

原文:https://www.cnblogs.com/lwl80/p/13386915.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!