Java多线程--两个线程同时对一个人的年龄进行增加和修改
2021-04-07 16:26
标签:res loading extends run http ring ++ idt sync Java多线程--两个线程同时对一个人的年龄进行增加和修改 标签:res loading extends run http ring ++ idt sync 原文地址:https://www.cnblogs.com/lwl80/p/13386915.html 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 ) {
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 ) {
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 }
上一篇:什么是算法?试从日常生活中找3个例子,描述它们的算法
下一篇:java设计模式应用
文章标题:Java多线程--两个线程同时对一个人的年龄进行增加和修改
文章链接:http://soscw.com/index.php/essay/72468.html