亲宝软件园·资讯

展开

Java多线程银行存钱

小虚竹and掘金 人气:0

多线程6(模拟银行系统存钱)

1.题目

模拟一个简单的银行系统,使用两个不同的线程向同一个账户存钱。

实现:使用synchronized关键字,将存钱的方法修改成同步的。

2.解题思路

创建一个类:SynchronizedBankFrame,继承JFrame类

写一个内部类Bank

写一个内部类Transfer,实现Runnable接口

在run方法中实现向账户存钱的功能。

同步方法就是用synchronized关键字修饰的方法。

JDK为每个JAVA对象配置了内置锁,如果方法使用synchronized关键字修饰,内置锁就会保护整个方法。

3.代码详解

SynchronizedBankFrame

package com.xiaoxuzhu;
import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.UIManager;
/**
 * Description:
 *
 * @author xiaoxuzhu
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本	        修改人		修改日期			修改内容
 * 2022/5/14.1	    xiaoxuzhu		2022/5/14		    Create
 * </pre>
 * @date 2022/5/14
 */

public class SynchronizedBankFrame extends JFrame {

    /**
     *
     */
    private static final long serialVersionUID = 2671056183299397274L;
    private JPanel contentPane;
    private JTextArea thread1TextArea;
    private JTextArea thread2TextArea;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    SynchronizedBankFrame frame = new SynchronizedBankFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public SynchronizedBankFrame() {
        setTitle("使用Synchronized实现线程同步");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));

        JPanel buttonPanel = new JPanel();
        contentPane.add(buttonPanel, BorderLayout.SOUTH);

        JButton startButton = new JButton("开始存钱");
        startButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                do_button_actionPerformed(arg0);
            }
        });
        buttonPanel.add(startButton);

        JPanel processPanel = new JPanel();
        contentPane.add(processPanel, BorderLayout.CENTER);
        processPanel.setLayout(new GridLayout(1, 2, 5, 5));

        JPanel thread1Panel = new JPanel();
        processPanel.add(thread1Panel);
        thread1Panel.setLayout(new BorderLayout(0, 0));

        JLabel thread1Label = new JLabel("一号线程");
        thread1Label.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        thread1Label.setHorizontalAlignment(SwingConstants.CENTER);
        thread1Panel.add(thread1Label, BorderLayout.NORTH);

        JScrollPane thread1ScrollPane = new JScrollPane();
        thread1Panel.add(thread1ScrollPane, BorderLayout.CENTER);

        thread1TextArea = new JTextArea();
        thread1TextArea.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        thread1ScrollPane.setViewportView(thread1TextArea);

        JPanel thread2Panel = new JPanel();
        processPanel.add(thread2Panel);
        thread2Panel.setLayout(new BorderLayout(0, 0));

        JLabel thread2Label = new JLabel("二号线程");
        thread2Label.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        thread2Label.setHorizontalAlignment(SwingConstants.CENTER);
        thread2Panel.add(thread2Label, BorderLayout.NORTH);

        JScrollPane thread2ScrollPane = new JScrollPane();
        thread2Panel.add(thread2ScrollPane, BorderLayout.CENTER);

        thread2TextArea = new JTextArea();
        thread2TextArea.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        thread2ScrollPane.setViewportView(thread2TextArea);
    }

    protected void do_button_actionPerformed(ActionEvent arg0) {
        Bank bank = new Bank();
        Thread thread1 = new Thread(new Transfer(bank, thread1TextArea));
        thread1.start();
        Thread thread2 = new Thread(new Transfer(bank, thread2TextArea));
        thread2.start();
    }

    private class Transfer implements Runnable {
        private Bank bank;
        private JTextArea textArea;

        public Transfer(Bank bank, JTextArea textArea) {// 初始化变量
            this.bank = bank;
            this.textArea = textArea;
        }

        public void run() {
            for (int i = 0; i < 10; i++) {// 向账户中存入10次钱
                bank.deposit(10);// 向账户中存入10块钱
                String text = textArea.getText();// 获得文本域中的文本
                // 在文本域中显示账户中的余额
                textArea.setText(text + "账户的余额是:" + bank.getAccount() + "\n");
            }
        }
    }

    private class Bank {
        private int account = 100;// 每个账户的初始金额是100元

        public synchronized void deposit(int money) {// 向账户中存入money元
            account += money;
        }

        public int getAccount() {// 查询账户余额
            return account;
        }
    }

}

加载全部内容

相关教程
猜你喜欢
用户评论