Experimento 5 Programación de subprocesos múltiples en Java

Objetivo

  1. Domina el método de la interfaz Runnable para realizar subprocesos múltiples
  2. Domina el uso de la clase Thread para realizar subprocesos múltiples
  3. Domina los métodos básicos de programación multihilo en lenguaje Java

contenido experimental

  1. Relevo de hilos ( 45 puntos)

Escriba una aplicación que, además del hilo principal, tenga tres hilos: primero, segundo y tercero. El primero se encarga de simular el movimiento de un botón rojo desde las coordenadas (10, 60) a (100, 60); el segundo se encarga de simular el movimiento de un botón verde desde las coordenadas (100, 60) a (200, 60). El tercer hilo se encarga de simular el movimiento de un botón azul desde las coordenadas (200, 60) a las (300, 60).

primer paso

El siguiente es el eclipse tutorial de la idea jdk1.8.

Crear una nueva clase MoveButton

 

El segundo paso es pegar la cobertura del código.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class MoveButton extends Frame implements Runnable, ActionListener {
	Thread first, second, third;    //用Thread类声明first,second,third三个线程对象
	Button redButton, greenButton, blueButton, startButton;     //声明四个按钮
	JLabel copyright;        //版权信息
	int distance = 10;

	MoveButton() {
		//分别创建first,second,third三个线程,用当前窗口做为该线程的目标对象.
		first = new Thread(this);
		second = new Thread(this);
		third = new Thread(this);

		redButton = new Button();
		greenButton = new Button();
		blueButton = new Button();

		redButton.setBackground(Color.red);
		greenButton.setBackground(Color.green);
		blueButton.setBackground(Color.blue);

		startButton = new Button("start");
		startButton.addActionListener(this);
		setLayout(null);
		add(redButton);
		copyright = new JLabel("xxxxxxx写自己的信息xxxxxxxx");
		add(copyright);
		redButton.setBounds(10, 60, 15, 15);
		add(greenButton);
		greenButton.setBounds(100, 60, 15, 15);
		add(blueButton);
		blueButton.setBounds(200, 60, 15, 15);
		add(startButton);

		startButton.setBounds(10, 100, 30, 30);
		copyright.setBounds(100, 100, 240, 30);
		setTitle("线程接力");
		setBounds(0, 0, 400, 200);
		setVisible(true);
		validate();
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			//分别启动三个线程
			first.start();
			second.start();
			third.start();
		} catch (Exception exp) {
		}
	}

	public void run() {
		while (true) {
			//判断当前占有CPU资源的线程是否是first
			if (Thread.currentThread() == first) {
				moveComponent(redButton);
				try {
					Thread.sleep(20);
				} catch (Exception exp) {
				}
			}
			//判断当前占有CPU资源的线程是否是second
			if (Thread.currentThread() == second) {
				moveComponent(greenButton);
				try {
					Thread.sleep(10);
				} catch (Exception exp) {
				}
			}
			//判断当前占有CPU资源的线程是否是third
			if (Thread.currentThread() == third) {
				moveComponent(blueButton);
				try {
					Thread.sleep(20);
				} catch (Exception e) {
				}
			}
		}
	}

	public synchronized void moveComponent(Component b) {
		if (Thread.currentThread() == first) {
			while (distance > 100 && distance <= 300)
				try {
					wait();
				} catch (Exception exp) {
				}
			distance = distance + 1;
			b.setLocation(distance, 60);
			if (distance >= 100) {
				b.setLocation(10, 60);
				notifyAll();
			}
		}
		if (Thread.currentThread() == second) {
			while (distance > 200 && distance <= 300)
				try {
					wait();
				} catch (Exception exp) {
				}
			distance = distance + 1;
			b.setLocation(distance, 60);
			if (distance > 200) {
				b.setLocation(100, 60);
				notifyAll();
			}
		}
		if (Thread.currentThread() == third) {
			while (distance > 300)
				try {
					wait();
				} catch (Exception exp) {
				}
			distance = distance + 1;
			b.setLocation(distance, 60);
			if (distance > 300) {
				distance = 10;
				b.setLocation(200, 60);
				notifyAll();
			}
		}
	}

	public static void main(String[] args) {
		new MoveButton().setLocationRelativeTo(null);
	}
}

El tercer paso es cambiar tu número de estudiante

 

2. Control de hilos

Escriba un programa que anime una cadena en un campo de texto. Agregue tres botones al sur del formulario para agregar la función de control de subprocesos al programa. Se requiere hacer clic en el botón de inicio (startBtn), el subproceso comienza a comenzar, el texto se muestra uno por uno y el estado del botón cambia. a deshabilitado (porque el hilo no se puede iniciar repetidamente); haga clic para pausar el botón (pauseBtn), el hilo se detiene y la visualización del texto se detiene; haga clic en el botón de reanudar (resumeBtn), el hilo se reanuda y el texto continúa mostrándose. Cuando el subproceso termine de ejecutarse, restaure el estado del botón de inicio a disponible.

Primer paso clave nueva clase RunnableDemo

 El segundo paso es pegar el código y taparlo.

import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.border.BevelBorder;
public class RunnableDemo extends JFrame implements Runnable, ActionListener {

    private JTextArea textArea; //文本域组件
    JLabel label;
    JButton startBtn;
    JButton pauseBtn;
    JButton resumeBtn;
    Panel panel;
    Thread thread;
    boolean move = false;

    //动画显示的文本字符串
    private final String introduction = "现在大家已经对计算机很熟悉了,如今计算机的操作"
            + "系统可以同时执行多个任务,在听歌的同时能够打字、下载文件,在聊天窗口打"
            + "字的时候,对方同时还能通过视频看到你;听到你。这一切都是使用多任务实现"
            + "的,Java语言使用多线程实现一个程序中的多个任务同时运行。程序员可以在程"
            + "序中执行多个线程,每一个线程完成一个功能,并与其他线程并发执行,这种机"
            + "制被称为多线程。";

    public RunnableDemo() {
        setTitle("线程的控制");
        label = new JLabel("多线程简介:xxxxxxx写自己的信息xxxxxxxx");//标签组件
        getContentPane().add(label, BorderLayout.NORTH);            //添加标签到窗体
        textArea = new JTextArea("\t");                             //初始化文本域组件
        textArea.setBorder(new BevelBorder(BevelBorder.LOWERED));   //设置边框
        textArea.setLineWrap(true);                                 //设置自动折行
        getContentPane().add(textArea, BorderLayout.CENTER);        //添加文本域组件到文本框
        startBtn = new JButton("开始");
        pauseBtn = new JButton("暂停");
        resumeBtn = new JButton("恢复");
        startBtn.addActionListener(this);
        pauseBtn.addActionListener(this);
        resumeBtn.addActionListener(this);
        panel = new Panel();
        panel.add(startBtn);
        panel.add(pauseBtn);
        panel.add(resumeBtn);
        getContentPane().add(panel, BorderLayout.SOUTH);
        setBounds(0, 0, 383, 225); //设置窗体大小位置
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true); //显示窗体
    }

    @Override   //Runnable接口方法,是线程的执行方法.
    public void run() {
        textArea.setText("\t");
        String[] intros = introduction.split(""); //将字符串分割为数组
        for (String ch : intros) {//ForEach遍历字符串数组
            while (!move) {
                try {
                    synchronized (this) {
                        wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            textArea.append(ch); //添加一个字符到文本域
            try {
                Thread.sleep(100); //线程休眠0.1秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        startBtn.setEnabled(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == startBtn) {
            thread = new Thread(this);
            thread.start();
            move = true;
        } else if (e.getSource() == pauseBtn) {
            move = false;
        } else if (e.getSource() == resumeBtn) {
            move = true;
            synchronized (this){
                notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        new RunnableDemo().setLocationRelativeTo(null); //创建本类实例对象
    }
}

cambiar el nombre aquí 

Supongo que te gusta

Origin blog.csdn.net/m0_59054762/article/details/130585264
Recomendado
Clasificación