Java多線程解決龜兔賽跑問題詳解

多線程4(龜兔賽跑-休眠線程)

1.題目

在龜兔賽跑中,領先的兔子因為通宵寫博客,中途太累睡著瞭,跑輸瞭烏龜。這個故事說明瞭兔子是愛學習的同學。咳咳,通宵是不可取的,大傢別學。

實現:使用線程休眠模擬龜兔賽跑比賽

2.解題思路

創建一個類:RaceFrame,繼承瞭JFrame。用來界面顯示兩個文本區域,用來輸出烏龜和兔子的比賽記錄,比賽開始按鈕用來開始比賽。

編寫內部類:Rabbit,該類實現瞭Runnable接口,在run()方法中,讓兔子休眠瞭時間。

Thread是程序中的執行線程。JAVA虛擬機允許應用程序並發地運行多個執行線程。

sleep()方法是Thread類的一個靜態方法。

3.代碼詳解

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 java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.UIManager;
import java.awt.Font;
/**
 * Description: 
 *
 * @author xiaoxuzhu
 * @version 1.0
 *
 * <pre>
 * 修改記錄:
 * 修改後版本	        修改人		修改日期			修改內容
 * 2022/5/11.1	    xiaoxuzhu		2022/5/11		    Create
 * </pre>
 * @date 2022/5/11
 */

public class RaceFrame extends JFrame {

    /**
     *
     */
    private static final long serialVersionUID = 4941729012450153307L;
    private JPanel contentPane;
    private JTextArea rabbitTextArea;
    private JTextArea tortoiseTextArea;

    /**
     * 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 {
                    RaceFrame frame = new RaceFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public RaceFrame() {
        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 button = new JButton("比賽開始");
        button.setFont(new Font("微軟雅黑", Font.PLAIN, 16));
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                do_button_actionPerformed(arg0);
            }
        });
        buttonPanel.add(button);

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

        JPanel rabbitPanel = new JPanel();
        panel.add(rabbitPanel);
        rabbitPanel.setLayout(new BorderLayout(0, 0));

        JLabel rabbitLabel = new JLabel("兔子的比賽記錄");
        rabbitLabel.setFont(new Font("微軟雅黑", Font.PLAIN, 16));
        rabbitLabel.setHorizontalAlignment(SwingConstants.CENTER);
        rabbitPanel.add(rabbitLabel, BorderLayout.NORTH);

        JScrollPane rabbitScrollPane = new JScrollPane();
        rabbitPanel.add(rabbitScrollPane, BorderLayout.CENTER);

        rabbitTextArea = new JTextArea();
        rabbitTextArea.setFont(new Font("微軟雅黑", Font.PLAIN, 16));
        rabbitScrollPane.setViewportView(rabbitTextArea);

        JPanel tortoisePanel = new JPanel();
        panel.add(tortoisePanel);
        tortoisePanel.setLayout(new BorderLayout(0, 0));

        JLabel tortoiseLabel = new JLabel("烏龜的比賽記錄");
        tortoiseLabel.setFont(new Font("微軟雅黑", Font.PLAIN, 16));
        tortoiseLabel.setHorizontalAlignment(SwingConstants.CENTER);
        tortoisePanel.add(tortoiseLabel, BorderLayout.NORTH);

        JScrollPane tortoiseScrollPane = new JScrollPane();
        tortoisePanel.add(tortoiseScrollPane, BorderLayout.CENTER);

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

    protected void do_button_actionPerformed(ActionEvent arg0) {
        Runnable run1 = new Rabbit();
        Runnable run2 = new Tortoise();
        Thread rabbit = new Thread(run1);
        Thread tortoise = new Thread(run2);
        rabbit.start();
        tortoise.start();
    }

    private class Rabbit implements Runnable {
        @Override
        public void run() {
            for (int i = 1; i < 11; i++) {// 循環10次模擬賽跑的過程
                String text = rabbitTextArea.getText();// 獲得文本域中的信息
                try {
                    Thread.sleep(1);// 線程休眠0.001秒,模擬兔子在跑步
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                rabbitTextArea.setText(text + "兔子跑瞭" + i + "0米\n");// 顯示兔子的跑步距離
                if (i == 9) {
                    rabbitTextArea.setText(text + "兔子在睡覺\n");// 當跑瞭90米時開始睡覺
                    try {
                        Thread.sleep(10000);// 線程休眠10秒,模擬兔子在睡覺
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (i == 10) {
                    try {
                        Thread.sleep(1);// 線程休眠0.001秒,模擬兔子在跑步
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    rabbitTextArea.setText(text + "兔子到達終點\n");// 顯示兔子到達瞭終點
                }
            }
        }
    }

    private class Tortoise implements Runnable {

        @Override
        public void run() {
            for (int i = 1; i < 11; i++) {
                String text = tortoiseTextArea.getText();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                tortoiseTextArea.setText(text + "烏龜跑瞭" + i + "0米\n");
                if (i == 10) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    tortoiseTextArea.setText(text + "烏龜到達終點\n");
                }
            }

        }

    }
}

到此這篇關於Java多線程解決龜兔賽跑問題詳解的文章就介紹到這瞭,更多相關Java多線程內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: