2024年11月Java如何实现线程同步?线程同步的方法和反面教材

发布时间:

  ⑴* Java线程:线程的同步

  ⑵* author leizhimin -- ::

  ⑶public class Test {

  ⑷public static void main(String[] args) {

  ⑸User u = new User("张三", );

  ⑹MyThread t = new MyThread("线程A", u, );

  ⑺MyThread t = new MyThread("线程B", u, -);

  ⑻MyThread t = new MyThread("线程C", u, -);

  ⑼MyThread t = new MyThread("线程D", u, -);

  ⑽MyThread t = new MyThread("线程E", u, );

  ⑾MyThread t = new MyThread("线程F", u, );

  ⑿t.start();

  ⒀t.start();

  ⒁t.start();

  ⒂t.start();

  ⒃t.start();

  ⒄t.start();

  ⒅class MyThread extends Thread {

  ⒆private User u;

  ⒇private int y = ;

  ⒈MyThread(String name, User u, int y) {

  ⒉super(name);

  ⒊this.u = u;

  ⒋this.y = y;

  ⒌public void run() {

  ⒍u.oper(y);

  ⒎class User {

  ⒏private String code;

  ⒐private int cash;

  ⒑User(String code, int cash) {

  ⒒this.code = code;

  ⒓this.cash = cash;

  ⒔public String getCode() {

  ⒕return code;

  ⒖public void setCode(String code) {

  ⒗this.code = code;

  ⒘* param x 添加x万元

  ⒙public synchronized void oper(int x) {

  ⒚Thread.sleep(L);

  ⒛this.cash += x;

  ①System.out.println(Thread.currentThread().getName() + "运行结束,增加“" + x + "”,当前用户账户余额为:" + cash);

  ②Thread.sleep(L);

  ③} catch (InterruptedException e) {

  ④e.printStackTrace();

  ⑤Override

  ⑥public String toString() {

  ⑦return "User{" +

  ⑧"code='" + code + ''' +

  ⑨", cash=" + cash +