欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java實(shí)現(xiàn)新建有返回值的線程的示例詳解

 更新時(shí)間:2022年09月26日 09:24:18   作者:小虛竹and掘金  
本文主要介紹了一個(gè)Java多線程的例題,題目是:使用ThreadLocal管理一號(hào)和二號(hào)線程,分別存入100元,在三號(hào)線程中使用利用一號(hào)和二號(hào)的計(jì)算結(jié)果來算出賬戶的實(shí)際金額。感興趣的可以了解一下

一、題目描述

題目:使用ThreadLocal管理一號(hào)和二號(hào)線程,分別存入100元,在三號(hào)線程中使用利用一號(hào)和二號(hào)的計(jì)算結(jié)果來算出賬戶的實(shí)際金額。

二、解題思路

創(chuàng)建一個(gè)類:SynchronizedBankFrame,繼承JFrame類

寫一個(gè)內(nèi)部類Bank

  • 定義一個(gè)account變量,來表示賬戶。
  • deposit():一個(gè)存錢的方法
  • getAccount():顯示賬戶余額的方法。

寫一個(gè)內(nèi)部類Transfer,實(shí)現(xiàn)Callable接口

在重寫call()方法時(shí),將返回值設(shè)置成賬戶的余額。

編寫do_button_actionPerformed()方法,用來監(jiān)聽單擊“開始存錢”按鈕事件。在該方法中,分別獲得了兩個(gè)ThreadLocal變量的結(jié)果并計(jì)算最后的存錢結(jié)果。

Callabler接口類似于Runnable,區(qū)別在于Callabler會(huì)返回結(jié)果。

Future接口表示異步計(jì)算的結(jié)果。它提供了檢查計(jì)算是否完成的方法,以等待計(jì)算的完成,并獲取計(jì)算的結(jié)果。計(jì)算完成后,只能使用get()方法來獲取結(jié)果。如果有必要,可以在計(jì)算完成前阻塞此方法。

三、代碼詳解

SynchronizedBankFrame

package com.xiaoxuzhu;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import java.awt.Font;
import javax.swing.UIManager;
/**
 * Description: 
 *
 * @author xiaoxuzhu
 * @version 1.0
 *
 * <pre>
 * 修改記錄:
 * 修改后版本	        修改人		修改日期			修改內(nèi)容
 * 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;
    private JTextArea thread3TextArea;

    /**
     * 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("新建有返回值的線程");
        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(0, 3, 5, 5));

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

        JLabel thread1Label = new JLabel("一號(hào)線程");
        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("二號(hào)線程");
        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);

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

        JLabel thread3Label = new JLabel("三號(hào)線程");
        thread3Label.setFont(new Font("微軟雅黑", Font.PLAIN, 16));
        thread3Label.setHorizontalAlignment(SwingConstants.CENTER);
        thread3Panel.add(thread3Label, BorderLayout.NORTH);

        JScrollPane thread3ScrollPane = new JScrollPane();
        thread3Panel.add(thread3ScrollPane, BorderLayout.CENTER);

        thread3TextArea = new JTextArea();
        thread3TextArea.setFont(new Font("微軟雅黑", Font.PLAIN, 16));
        thread3ScrollPane.setViewportView(thread3TextArea);
    }

    protected void do_button_actionPerformed(ActionEvent arg0) {
        Bank bank = new Bank();
        Transfer transfer1 = new Transfer(bank, thread1TextArea);// 創(chuàng)建Transfer對(duì)象
        Transfer transfer2 = new Transfer(bank, thread2TextArea);// 創(chuàng)建Transfer對(duì)象
        FutureTask<Integer> task1 = new FutureTask<Integer>(transfer1);// 創(chuàng)建FutureTask對(duì)象
        FutureTask<Integer> task2 = new FutureTask<Integer>(transfer2);// 創(chuàng)建FutureTask對(duì)象
        Thread thread1 = new Thread(task1);// 創(chuàng)建一號(hào)線程
        Thread thread2 = new Thread(task2);// 創(chuàng)建二號(hào)線程
        thread1.start();// 運(yùn)行一號(hào)線程
        thread2.start();// 運(yùn)行二號(hào)線程
        try {
            int thread1Result = task1.get();// 獲得一號(hào)線程的計(jì)算結(jié)果
            int thread2Result = task2.get();// 獲得二號(hào)線程的計(jì)算結(jié)果
            thread3TextArea.setText(thread3TextArea.getText() + "一號(hào)計(jì)算結(jié)果是:" + thread1Result + "\n");// 更新三號(hào)線程文本域信息
            thread3TextArea.setText(thread3TextArea.getText() + "二號(hào)計(jì)算結(jié)果是:" + thread2Result + "\n");// 更新三號(hào)線程文本域信息
            thread3TextArea.setText(thread3TextArea.getText() + "實(shí)際的金額是:" + (thread1Result + thread2Result - 100) + "\n");// 更新三號(hào)線程文本域信息
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}

Bank

public class Bank {
    private static ThreadLocal<Integer> account = new ThreadLocal<Integer>() {

        @Override
        protected Integer initialValue() {
            return 100;
        }

    };

    public void deposit(int money) {
        account.set(account.get() + money);
    }

    public int getAccount() {
        return account.get();
    }
}

Transfer

package com.xiaoxuzhu;
import java.util.concurrent.Callable;

import javax.swing.JTextArea;
/**
 * Description: 
 *
 * @author xiaoxuzhu
 * @version 1.0
 *
 * <pre>
 * 修改記錄:
 * 修改后版本	        修改人		修改日期			修改內(nèi)容
 * 2022/5/14.1	    xiaoxuzhu		2022/5/14		    Create
 * </pre>
 * @date 2022/5/14
 */
public class Transfer implements Callable<Integer> {
    private Bank bank;
    private JTextArea textArea;

    public Transfer(Bank bank, JTextArea textArea) {// 利用構(gòu)造方法初始化變量
        this.bank = bank;
        this.textArea = textArea;
    }

    public Integer call() {
        for (int i = 0; i < 10; i++) {// 循環(huán)10次向賬戶中存錢
            bank.deposit(10);
            String text = textArea.getText();
            textArea.setText(text + "賬戶的余額是:" + bank.getAccount() + "\n");
        }
        return bank.getAccount();// 獲得賬戶的余額
    }
}

以上就是Java實(shí)現(xiàn)新建有返回值的線程的示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Java新建有返回值線程的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論