实验五 Java多线程程序设计

打印 上一主题 下一主题

主题 923|帖子 923|积分 2769

目的

1.    掌握Runnable接口实现多线程的方法

2.    掌握Thread类实现多线程的用法

3.    掌握Java语言中多线程编程的基本方法

1. 线程接力(45分)

要求:编写一个应用程序,除了主线程外,还有三个线程:first、second和third。
first负责模拟一个红色的按钮从坐标(10,60)运动到(100,60);
second负责模拟一个绿色的按钮从坐标(100,60)运动到(200,60);
third线程负责模拟一个蓝色的按钮从坐标(200,60)运动到(300,60)。

2. 线程的控制(45分)

要求:编写一个程序,动画显示文本域中的字符串。在窗体的南面添加三个按钮,为程序添加线程控制功能。
点击开始按钮(startBtn),线程开始启动,文字逐个显示,并且将按钮状态改变为禁用(因为线程不能重复启动)
点击暂停按钮(pauseBtn),线程暂停,文字显示停止
点击恢复按钮(resumeBtn),线程恢复运行,文字继续显示
当线程执行完毕后,恢复开始按钮的状态为可用。

线程接力
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. public class MoveButton extends Frame implements Runnable, ActionListener {
  5.     // 用Thread类声明first,second,third三个线程对象
  6.         Thread first,second,third;
  7.     Button redButton, greenButton, blueButton, startButton;
  8.     int distance = 10;
  9.     MoveButton() {
  10.         //分别创建first,second,third三个线程,用当前窗口做为该线程的目标对象
  11.         first =new Thread(this);
  12.         second = new Thread(this);
  13.         third = new Thread(this);
  14.         redButton = new Button();
  15.         greenButton = new Button();
  16.         blueButton = new Button();
  17.         redButton.setBackground(Color.red);
  18.         greenButton.setBackground(Color.green);
  19.         blueButton.setBackground(Color.blue);
  20.         startButton = new Button("start");
  21.         startButton.addActionListener(this);
  22.         setLayout(null);
  23.         add(redButton);
  24.         redButton.setBounds(10, 60, 15, 15);
  25.         add(greenButton);
  26.         greenButton.setBounds(100, 60, 15, 15);
  27.         add(blueButton);
  28.         blueButton.setBounds(200, 60, 15, 15);
  29.         add(startButton);
  30.         startButton.setBounds(10, 100, 30, 30);
  31.         JLabel label1 = new JLabel("your name   不啦不啦不啊咯");
  32.         add(label1);
  33.         label1.setBounds(50, 105, 150, 25);
  34.         setTitle("线程接力");
  35.         setBounds(0, 0, 400, 200);
  36.         setVisible(true);
  37.         validate();
  38.         addWindowListener(new WindowAdapter() {
  39.             public void windowClosing(WindowEvent e) {
  40.                                 System.exit(0);
  41.             }
  42.         });
  43.     }
  44.     public void actionPerformed(ActionEvent e) {
  45.         try {
  46.             // 分别启动三个线程
  47.             first.start();
  48.             second.start();
  49.             third.start();
  50.         } catch (Exception exp) {
  51.         }
  52.     }
  53.     public void run() {
  54.         while (true) {
  55.             // 判断当前占有CPU资源的线程是否是first
  56.             if (Thread.currentThread()==first) {
  57.                 moveComponent(redButton);
  58.                 try {
  59.                     Thread.sleep(20);
  60.                 } catch (Exception exp) {
  61.                 }
  62.             }
  63. // 判断当前占有CPU资源的线程是否是second
  64.             if (Thread.currentThread()==second) {
  65.                 moveComponent(greenButton);
  66.                 try {
  67.                     Thread.sleep(10);
  68.                 } catch (Exception exp) {
  69.                 }
  70.             }
  71. // 判断当前占有CPU资源的线程是否是third
  72.             if (Thread.currentThread()==third) {
  73.                 moveComponent(blueButton);
  74.                 try {
  75.                     Thread.sleep(20);
  76.                 } catch (Exception e) {
  77.                 }
  78.             }
  79.         }
  80.     }
  81.     public synchronized void moveComponent(Component b) {
  82.         if (Thread.currentThread() == first) {
  83.             while (distance > 100 && distance <= 300)
  84.                 try {
  85.                     wait();
  86.                 } catch (Exception exp) {
  87.                 }
  88.             distance = distance + 1;
  89.             b.setLocation(distance, 60);
  90.             if (distance >= 100) {
  91.                 b.setLocation(10, 60);
  92.                 notifyAll();
  93.             }
  94.         }
  95.         if (Thread.currentThread() == second) {
  96.             while ((distance>10 && distance<100) && (distance>200 && distance<300) )
  97.                 try {
  98.                     wait();
  99.                 } catch (Exception exp) {
  100.                 }
  101.             distance = distance + 1;
  102.             b.setLocation(distance, 60);
  103.             if (distance > 200) {
  104.                 b.setLocation(100, 60);
  105.                 notifyAll();
  106.             }
  107.         }
  108.         if (Thread.currentThread() == third) {
  109.             while (distance<200)
  110.                 try {
  111.                     wait();
  112.                 } catch (Exception exp) {
  113.                 }
  114.             distance = distance + 1;
  115.             b.setLocation(distance, 60);
  116.             if (distance > 300) {
  117.                 distance = 10;
  118.                 b.setLocation(200, 60);
  119.                 notifyAll();
  120.             }
  121.         }
  122.     }
  123.     public static void main(String[] args) {
  124.         new MoveButton().setLocationRelativeTo(null);
  125.     }
  126. }
复制代码
程序运行截图

自己截图粘贴进markdown
实验总结

“线程接力”体现了Java多线程编程的线程切换特性,通过三个线程对一个组件进行移动,实现了多个线程间的协同作用。
线程的控制
  1. import java.awt.*;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import javax.swing.*;
  5. import javax.swing.border.BevelBorder;
  6. public class RunnableDemo extends JFrame implements Runnable, ActionListener {
  7.     private JTextArea textArea; // 文本域组件
  8.     JLabel label;
  9.     Button startBtn, pauseBtn, resumeBtn;
  10.     Panel panel;
  11.     Thread thread;
  12.     boolean move = false;
  13.     // 动画显示的文本字符串
  14.     private String introduction = "现在大家已经对计算机很熟悉了,如今计算机的操作"
  15.             + "系统可以同时执行多个任务,在听歌的同时能够打字、下载文件,在聊天窗口打"
  16.             + "字的时候,对方同时还能通过视频看到你;听到你。这一切都是使用多任务实现"
  17.             + "的,Java语言使用多线程实现一个程序中的多个任务同时运行。程序员可以在程"
  18.             + "序中执行多个线程,每一个线程完成一个功能,并与其他线程并发执行,这种机"
  19.             + "制被称为多线程。";
  20.     public static void main(String args[]) {
  21.         new RunnableDemo().setLocationRelativeTo(null); // 创建本类实例对象
  22.     }
  23.     public RunnableDemo() {
  24.         setTitle("线程的控制");
  25.         label = new JLabel("多线程简介: your name   不啦不啦不啊咯"); // 标签组件
  26.         getContentPane().add(label, BorderLayout.NORTH);// 添加标签到窗体
  27.         textArea = new JTextArea("\t"); // 初始化文本域组件
  28.         textArea.setBorder(new BevelBorder(BevelBorder.LOWERED));// 设置边框
  29.         textArea.setLineWrap(true); // 设置自动折行
  30.         getContentPane().add(textArea, BorderLayout.CENTER);// 添加文本域组件到文本框
  31.         startBtn = new Button("开始");
  32.         pauseBtn = new Button("暂停");
  33.         resumeBtn = new Button("恢复");
  34.         startBtn.addActionListener(this);
  35.         pauseBtn.addActionListener(this);
  36.         resumeBtn.addActionListener(this);
  37.         panel = new Panel();
  38.         panel.add(startBtn);
  39.         panel.add(pauseBtn);
  40.         panel.add(resumeBtn);
  41.         getContentPane().add(panel, BorderLayout.SOUTH);
  42.         setBounds(0, 0, 383, 225); // 设置窗体大小位置
  43.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  44.         setVisible(true); // 显示窗体
  45.     }
  46.     /**
  47.      * Runnable接口方法,是线程的执行方法
  48.      */
  49.     @Override
  50.     public void run() {
  51.         textArea.setText("\t");
  52.         String[] intros = introduction.split(""); // 将字符串分割为数组
  53.         for (String ch : intros) { // ForEach遍历字符串数组
  54.             while (!move) {
  55.                 try {
  56.                     synchronized (this) {
  57.                         wait();
  58.                     }
  59.                 } catch (InterruptedException e) {
  60.                     e.printStackTrace();
  61.                 }
  62.             }
  63.             textArea.append(ch); // 添加一个字符到文本域
  64.             try {
  65.                 Thread.sleep(100); // 线程休眠0.1秒
  66.             } catch (InterruptedException e) {
  67.                 e.printStackTrace();
  68.             }
  69.         }
  70.         startBtn.setEnabled(true);
  71.     }
  72.     @Override
  73.     public void actionPerformed(ActionEvent e) {
  74.         if (e.getSource() == startBtn) {
  75.                 thread =new Thread(this);
  76.                         thread.start();
  77.                         move=true;
  78.                         startBtn.setEnabled(false);
  79.         } else if (e.getSource() == pauseBtn) {
  80.                 move=false;
  81.         } else if (e.getSource() == resumeBtn) {
  82.                 move=true;
  83.                 synchronized (this) {
  84.                                 notifyAll();
  85.                         }
  86.         }
  87.     }
  88. }
复制代码
程序运行截图

自己截图粘贴进markdown
实验总结

这个实例体现了Java多线程编程的线程控制特性,通过线程的控制实现了动画效果的实时调整。
Java多线程编程非常重要,能够提高程序运行效率,但同时也需要注意线程之间的协作和控制,避免死锁。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

干翻全岛蛙蛙

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表