【无标题】

package shiyan5;
import java.awt.*;
import java.awt.event.*;
public class MoveButton extends Frame implements Runnable, ActionListener {
	// 用Thread类声明first,second,third三个线程对象
	Thread first,second,third;                                                                     
	Button redButton, greenButton, blueButton, startButton;
	int distance = 10;
	MoveButton() {
		//分别创建first,second,third三个线程,用当前窗口做为该线程的目标对象
		first = new Thread(this);   //this是窗体实例的指针 ,this其实就是指当前正在运行的线程对象; 
		second = new Thread(this);  //this是窗体实例的指针                                                            ; 
		third = new Thread(this);  //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);					//窗体初始化
		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);
setTitle("线程接力");
		setBounds(0, 0, 400, 200);
		setVisible(true);
		validate();
		addWindowListener(new WindowAdapter() {			//给窗体注册关闭事件
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}

	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) //判断当前的线程是否是first
			{
				moveComponent(redButton);
				try {
					Thread.sleep(20);		//休眠20s
				} 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();					//配对底下的notifyAll,使线程处于等待状态
				} catch (Exception exp) {
				}
			distance = distance + 1;
			b.setLocation(distance, 60);
			if (distance >= 100) {
				b.setLocation(10, 60);		//按钮回到原点
				notifyAll();				//唤醒其他的线程
			}
		}
		if (Thread.currentThread() == second) {
			while ((distance >= 10 && distance < 100) || (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 >= 10 && distance < 200)
				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);
	}
}
package shiyan5;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.BevelBorder;
public class RunnableDemo extends JFrame implements Runnable, ActionListener {
	private JTextArea textArea; // 文本域组件
	JLabel label;
	Button startBtn, pauseBtn, resumeBtn;
	Panel panel;
	Thread thread;
	boolean move = false;

	// 动画显示的文本字符串
	private String introduction = "现在大家已经对计算机很熟悉了,如今计算机的操作"
			+ "系统可以同时执行多个任务,在听歌的同时能够打字、下载文件,在聊天窗口打"
			+ "字的时候,对方同时还能通过视频看到你;听到你。这一切都是使用多任务实现"
			+ "的,Java语言使用多线程实现一个程序中的多个任务同时运行。程序员可以在程"
			+ "序中执行多个线程,每一个线程完成一个功能,并与其他线程并发执行,这种机" 
			+ "制被称为多线程。";
	public static void main(String args[]) {
		new RunnableDemo().setLocationRelativeTo(null); // 创建本类实例对象
	}
	public RunnableDemo() {
		setTitle("线程的控制");
		label = new JLabel("多线程简介:"); // 标签组件
		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 Button("开始");	//按钮初始化
		pauseBtn = new Button("暂停");
		resumeBtn = new Button("恢复");
		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(JFrame.EXIT_ON_CLOSE);	//关闭事件
		setVisible(true); // 显示窗体
	}

	/**Runnable接口方法,是线程的执行方法*/
	@Override
	public void run() {
		textArea.setText("\t");				//缩进
		String[] intros = introduction.split(""); // 将字符串分割为数组
		for (String ch : intros) { // ForEach遍历字符串数组
			while (!move) {			//判断变量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;					//线程启动                                                     
			startBtn.setEnabled(false);     //按钮变为灰色	                                                
			                                                     
		} else if (e.getSource() == pauseBtn) {
			move = false;                                                    
		} else if (e.getSource() == resumeBtn) {
			move = true;                                                     
			synchronized (this) { 	//this是当前目标的实例
				notifyAll();	//唤醒处于休眠状态的程序                                                     
			}                                                     
			                                                     
			                                                     
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值