Java多线程--两个线程同时对一个人的年龄进行增加和修改
Posted 勤快的懒羊羊
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java多线程--两个线程同时对一个人的年龄进行增加和修改相关的知识,希望对你有一定的参考价值。
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多线程--两个线程同时对一个人的年龄进行增加和修改的主要内容,如果未能解决你的问题,请参考以下文章