码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-07-28 00:02:43      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:res   loading   extends   run   http   ring   ++   idt   sync   

 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多线程--两个线程同时对一个人的年龄进行增加和修改

标签:res   loading   extends   run   http   ring   ++   idt   sync   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!