第十二章 Java多线程程序设计·乙

本程序基于下面教材的例程修改
  尉哲明,冀素琴,郭珉. 基于Java的综合课程设计. 北京: 清华大学出版社, 2014(12).

案例:两按钮反向运动——使用Runnable接口

案例问题描述

  创建一个GUI程序,当单击“开始”按钮,界面中的两个按钮开始朝相反方向运动,单击“停止”按钮,两按钮同时停止运动。要求通过Thread类的子类来实现多线程,再现两按钮反向运动的情景。

案例练习题目

  (1)为该应用程序增加一个功能,用户可以控制按钮移动的速度(让用户可以控制按钮两次移动之间的时间间隔)。

//12_2_1

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class MoveButtonWindow extends JFrame implements ActionListener,Runnable
{
	
	JButton startButton,stopButton,exitButton;
	JButton rightButton,leftButton;
	Thread left,right;
	boolean boo=true;
	
	JButton accelerationButton,decelerationButton;
	int time=200;
	
	public MoveButtonWindow()
	{
		setTitle("测试多线程主窗口");
		JPanel centerPanel=new JPanel();
		JPanel controlPanel=new JPanel();
		add(centerPanel,BorderLayout.CENTER );
		add(controlPanel,BorderLayout.SOUTH );
		
		startButton=new JButton("开始/继续");
		startButton.addActionListener(this);
		stopButton=new JButton("停止");
		stopButton.addActionListener(this);
		exitButton=new JButton("退出");
		exitButton.addActionListener(this);
		accelerationButton=new JButton("加速");
		accelerationButton.addActionListener(this);
		decelerationButton=new JButton("减速");
		decelerationButton.addActionListener(this);
		
		controlPanel.add(this.startButton );
		controlPanel.add(this.stopButton );
		controlPanel.add(this.exitButton );
		controlPanel.add(this.accelerationButton);
		controlPanel.add(this.decelerationButton);
		
		centerPanel.setLayout(null);
		centerPanel.setBackground(Color.white );
		rightButton=new JButton("向右移动");
		rightButton.setBackground(Color.yellow );
		rightButton.setBounds(0, 5, 100, 30);
		leftButton=new JButton("向左移动");
		leftButton.setBackground(Color.red );
		leftButton.setBounds(385,90,100,30);
		centerPanel.add(rightButton);
		centerPanel.add(leftButton);
		
		right=new Thread(this);
		left=new Thread(this);
		
		setBounds(100,100,500,200);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
		this.setResizable(false);
		setVisible(true);
		validate();
		
	}

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		if(e.getSource()==this.startButton )
		{
			if(!right.isAlive())
			{
				right=new Thread(this);
			}
			
			if(!left.isAlive())
			{
				left=new Thread(this);
			}
			
			boo=true;
			right.start();
			left.start();
		}
		
		else if(e.getSource()==this.stopButton)
		{
			boo=false;
		}
		
		else if(e.getSource()==this.exitButton)
		{
			boo=false;
			System.exit(0);
		}
		
		else if(e.getSource()==this.accelerationButton)
		{
			time=time-20;
		}
		
		else if(e.getSource()==this.decelerationButton)
		{
			time=time+20;
		}
	}
	
	public static void main(String[] args) 
	{
		new MoveButtonWindow();
	}

	@Override
	public void run() 
	{
		while(true)
		{
			if(Thread.currentThread()==right)
			{
				int x=this.rightButton.getBounds().x;
				x=x+5;
				
				if(x>400)
				{
					x=5;
				}
				
				rightButton.setLocation(x, 5);
				
				try 
				{
					Thread.sleep(time);
				} 
				catch (InterruptedException e) 
				{
					e.printStackTrace();
				}
			}// end of if(Thread.currentThread()==right)
			
			
			else if(Thread.currentThread()==left)
			{
				int x=leftButton.getBounds().x;
				x=x-5;
				
				if(x<0)
				{
					x=385;
				}
				
				leftButton.setLocation(x, 90);
				
				try 
				{
					Thread.sleep(time);
				} 
				catch (InterruptedException e) 
				{
					e.printStackTrace();
				}
			}// end of else if(Thread.currentThread()==left)
			
			if(!boo)
			{
				return;
			}
		}//end of while(true)
	}
}

  (2)请设计一个使用Runnable接口实现多线程的程序,实现让两个人其中一个人报1~100的平方,另一个人报1~100的立方。

//12_2_2


public class TwelveTwoTwo implements Runnable
{
	//top报1~100的平方,bottom报1~100的立方
	Thread top,bottom;
	
	int topNum=1;
	int bottomNum=1;
	
	String Result;
	
	public TwelveTwoTwo()
	{
	  	top=new Thread(this);
	  	top.start();
	  	
	  	bottom=new Thread(this);
	  	bottom.start();
	}
	

	public void run() 
	{
		while(true)
		{
			//报1~100的平方
			if(Thread.currentThread()==top)
			{
				int result=topNum*topNum;
				System.out.println("top给出的数字为:"+result);
				topNum++;
				try
	            {
	                Thread.sleep(2000);
	            }
	            catch(InterruptedException e)
	            {
	                e.printStackTrace();
	            }	
			}
			
			//报1~100的立方
			else if(Thread.currentThread()==bottom)
			{
				int result=bottomNum*bottomNum*bottomNum;
				System.out.println("bottom给出的数字为:"+result);
				bottomNum++;
				try
	            {
	                Thread.sleep(2000);
	            }
	            catch(InterruptedException e)
	            {
	                e.printStackTrace();
	            }	
			}//else if(Thread.currentThread()==bottom)
		}
	}
  
	public static void main(String[] args) 
	{
		new TwelveTwoTwo();
	}
}

  (3)请设计一个使用Runnable接口实现多线程的程序,用两个小球模拟物理中的自由落体运动和平抛运动。

//12_2_3

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class TwelveTwoThree extends JFrame implements Runnable
{
	MyOval topOval,bottomOval;
	Color topColor,bottomColor;
	Thread top,bottom;
	
	boolean boo=true;
	
	public TwelveTwoThree()
	{
		setTitle("12_2_3");
		
		topColor=new Color(250,50,50);
		topOval=new MyOval(100,50,20,20,topColor,true);
		topOval.setV(0);
		
		bottomColor=new Color(200,50,50);
		bottomOval=new MyOval(100,50,20,20,bottomColor,false);
		bottomOval.setV(30);
		
		top=new Thread(this);
		bottom=new Thread(this);
		
		top.start();
		bottom.start();

		setBounds(100,100,600,600);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}

	
	public void paint(Graphics g)
	{
		super.paint(g);
		
		topOval.draw(g);
		bottomOval.draw(g);
	}
	
	
	@Override
	public void run() 
	{
		while(true)
		{
			if(Thread.currentThread()==top)
			{
				int x=topOval.getX();
				int y=topOval.getY();
				int t=topOval.getTime();
				int v=topOval.getV();
				
				t=topOval.getTim()+t;
				y=(int)(4.9*t*t)+50;
				x=v*t+100;
				
				try
				{
					Thread.sleep(800);
				}
				catch(InterruptedException e)
				{
					e.printStackTrace();
				}
				
				topOval.setX(x);
				topOval.setY(y);
				topOval.setTim(t);
				repaint();
				
				if(topOval.getY()>600)
					boo=false;
				else if(topOval.getX()>600)
					boo=false;
			}// end of if(Thread.currentThread()==top)
			
			
			else if(Thread.currentThread()==bottom)
			{
				int x=bottomOval.getX();
				int y=bottomOval.getY();
				int t=bottomOval.getTime();
				int v=bottomOval.getV();
				
				t=bottomOval.getTim()+t;
				y=(int)(4.9*t*t)+50;
				x=v*t+100;
				
				try
				{
					Thread.sleep(800);
				}
				catch(InterruptedException e)
				{
					e.printStackTrace();
				}
				
				bottomOval.setX(x);
				bottomOval.setY(y);
				bottomOval.setTim(t);
				repaint();
				
				if(bottomOval.getY()>600)
					boo=false;
				else if(bottomOval.getX()>600)
					boo=false;
			}// end of if(Thread.currentThread()==bottom)
			
			if(!boo)
				return;
		}//end of while(true)
	}


	public static void main(String[] args) 
	{
		new TwelveTwoThree();
	}
}
//12_2_3

import java.awt.Color;
import java.awt.Graphics;

public class MyOval 
{
	private int x,y,width,height;
	private Color color;
	private Boolean flag;
	
	private int time=1;			//间隔时长
	private int tim=0;			//总时长
	private int v=0;			//水平速度
	
	
	public MyOval()
	{
		this.x=0;
		this.y=0;
		this.width=0;
		this.height=0;
		this.color=Color.white;
		this.flag=true;
	}
	
	public MyOval(int x,int y,int width,int height,Color color,Boolean flag)
	{
		this.x=x;
		this.y=y;
		this.width=width;
		this.height=height;
		this.color=color;
		this.flag=flag;
	}
	
	public void draw(Graphics g)
	{
		g.setColor(color);
						
		if(flag)
			g.fillOval(x,y,width,height);
		else
			g.drawOval(x,y,width,height);
	}

	
	public int getX()
	{
		return x;
	}
	
	public void setX(int x)
	{
		this.x=x;
	}

	public int getY()
	{
		return y;
	}

	public void setY(int y)
	{
		this.y=y;
	}
	
	public int getTime()
	{
		return time;
	}
	
	public int getTim()
	{
		return tim;
	}
	
	public void setTim(int tim)
	{
		this.tim=tim;
	}
	
	public int getWidth()
	{
		return width;
	}
	
	public int getHeight()
	{
		return height;
	}

	public Boolean getFlag()
	{
		return flag;
	}
	
	public int getV()
	{
		return v;
	}
	
	public void setV(int v)
	{
		this.v=v;
	}
}

  (4)请设计一个使用Runnable接口实现多线程的程序,用两个小球模拟物理中的正弦函数和余弦函数曲线进行运动。

//12_2_4

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class TwelveTwoFour extends JFrame implements Runnable
{
	MyOval topOval,bottomOval;
	Color topColor,bottomColor;
	Thread top,bottom;
	
	boolean boo=true;
	
	public TwelveTwoFour()
	{
		setTitle("12_2_4");
		
		topColor=new Color(250,50,50);
		topOval=new MyOval(50,290,20,20,topColor,true);
		
		bottomColor=new Color(200,50,50);
		bottomOval=new MyOval(50,290,20,20,bottomColor,false);
		bottomOval.setIne(1);
		
		top=new Thread(this);
		bottom=new Thread(this);
		
		top.start();
		bottom.start();

		setBounds(100,100,600,600);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}

	
	public void paint(Graphics g)
	{
		super.paint(g);
		
		topOval.draw(g);
		bottomOval.draw(g);
		g.drawLine(0,300,600,300);
	}
	
	
	@Override
	public void run() 
	{
		while(true)
		{
			if(Thread.currentThread()==top)
			{
				double d=topOval.getDegree();
				double radian = Math.toRadians(d);
				
				int x=(int)(d+50);
				d=d+5;
				
				int y=(int)(290-Math.sin(radian)*100);
				
				try
				{
					Thread.sleep(400);
				}
				catch(InterruptedException e)
				{
					e.printStackTrace();
				}
				
				topOval.setX(x);
				topOval.setY(y);
				topOval.setDegree(d);
				repaint();
				
				if(topOval.getX()>600)
					boo=false;
			}// end of if(Thread.currentThread()==top)
			
			
			else if(Thread.currentThread()==bottom)
			{
				double d=bottomOval.getDegree();
				double radian = Math.toRadians(d);
				
				int x=(int)(d+50);
				d=d+5;
				
				int y=(int)(290-Math.cos(radian)*100);
				
				try
				{
					Thread.sleep(400);
				}
				catch(InterruptedException e)
				{
					e.printStackTrace();
				}
				
				bottomOval.setX(x);
				bottomOval.setY(y);
				bottomOval.setDegree(d);
				repaint();
				
				if(bottomOval.getX()>600)
					boo=false;
			}// end of if(Thread.currentThread()==bottom)
			
			if(!boo)
				return;
		}//end of while(true)
	}


	public static void main(String[] args) 
	{
		new TwelveTwoFour();
	}
}
//12_2_4

import java.awt.Color;
import java.awt.Graphics;

public class MyOval 
{
	private int x,y,width,height;
	private Color color;
	private Boolean flag;
	
	private int time=1;			//间隔时长
	private int tim=0;			//总时长
	private int v=0;			//水平速度
	
	private double degree=0;	//角度
	private int ine=0;			//零为正弦,一为余弦	
	
	public MyOval()
	{
		this.x=0;
		this.y=0;
		this.width=0;
		this.height=0;
		this.color=Color.white;
		this.flag=true;
	}
	
	public MyOval(int x,int y,int width,int height,Color color,Boolean flag)
	{
		this.x=x;
		this.y=y;
		this.width=width;
		this.height=height;
		this.color=color;
		this.flag=flag;
	}
	
	public void draw(Graphics g)
	{
		g.setColor(color);
						
		if(flag)
			g.fillOval(x,y,width,height);
		else
			g.drawOval(x,y,width,height);
	}

	
	public int getX()
	{
		return x;
	}
	
	public void setX(int x)
	{
		this.x=x;
	}

	public int getY()
	{
		return y;
	}

	public void setY(int y)
	{
		this.y=y;
	}
	
	public int getTime()
	{
		return time;
	}
	
	public int getTim()
	{
		return tim;
	}
	
	public void setTim(int tim)
	{
		this.tim=tim;
	}
	
	public int getWidth()
	{
		return width;
	}
	
	public int getHeight()
	{
		return height;
	}

	public Boolean getFlag()
	{
		return flag;
	}
	
	public int getV()
	{
		return v;
	}
	
	public void setV(int v)
	{
		this.v=v;
	}
	
	public double getDegree()
	{
		return degree;
	}
	
	public void setDegree(double degree)
	{
		this.degree=degree;
	}
	
	public int getIne()
	{
		return ine;
	}
	
	public void setIne(int ine)
	{
		this.ine=ine;
	}
}

  (5)请设计一个使用Runnable接口实现多线程的程序,实现猜数字游戏。一个线程负责随机给出一个1~100之间的正整数,另一个线程负责猜数字。

//12_2_5
/*
 * @author https://beishan.blog.csdn.net/?type=blog
 * @source https://beishan.blog.csdn.net/article/details/112393313?spm=1001.2014.3001.5502
 */

import java.util.Random;
 
public class TwelveTwoFive implements Runnable
{
	Thread top,bottom;
	
	int topN;
	int bottomMin=0,bottomMax=100,bottomN;
	
	String Result;
	
	public TwelveTwoFive()
	{
    	top=new Thread(this);
    	top.start();
    	
    	bottom=new Thread(this);
    	bottom.start();
	}
	

	public void run() 
    {
		if(Thread.currentThread()==top)
		{
	        //获取1~100的随机数
	        Random random=new Random();
	        topN=random.nextInt(100);
	        
	        System.out.println("top给出的数字为:"+topN);
		}
		
		else if(Thread.currentThread()==bottom)
		{
			while(true) 
	        {
	            try
	            {
	                Thread.sleep(2000);
	            }
	            catch(InterruptedException e)
	            {
	                e.printStackTrace();
	            }
	            
	            Random ran=new Random();
	            
	            //当前猜的数字(最大值和最小值之间的数)
	            bottomN=bottomMin+ran.nextInt(bottomMax-bottomMin);
	            
	            //调用给出整数的线程 的猜数字方法guessnum,
	            Result=guessnum(bottomN);
	            
	            if(Result.equals("猜小了")) 
	            {
	            	bottomMin=bottomN;
	                System.out.println("线程二猜的数字是:"+bottomN+"---猜小了");
	            }
	            
	            else if(Result.equals("猜大了")) 
	            {
	            	bottomMax=bottomN;
	                System.out.println("线程二猜的数字是:"+bottomN+"---猜大了");
	            }
	            
	            else
	            {
	                System.out.println("线程二猜的数字是:"+bottomN+"---猜对了,结果是"+bottomN);
	                System.exit(0);
	            }
	        }//end of while(true)
		}//else if(Thread.currentThread()==bottom)
    }
	
	//猜数字
    public String guessnum(int m) 
    {
        if(m<topN) 
        {
            return "猜小了";
        }
        
        else if(m>topN)
        {
            return "猜大了";
        }
        
        else return "猜对了";
    }
	
    //获取比较结果
    public String getGuess() 
    {
        return Result;
    }

    
    public static void main(String[] args) 
    {
    	new TwelveTwoFive();
    }
}
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
【完整课程列表】 https://download.csdn.net/download/qq_27595745/55555830 完整版精品java课件 Java基础入门教程 Java程序设计 第1章 Java语言概述(共38页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第2章 java语言基础(共31页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第3章 控制结构(共23页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第4章 类和对象(共57页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第5章 继承和接口(共47页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第6章 数组和集合(共44页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第7章 字符串处理(共38页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第8章 异常处理(共27页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第9章 输入输出流(共49页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第10章 JDBC数据库编程(共21页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第11章 图形用户界面1(共27页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第11章 图形用户界面2(共31页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第12章 applet(共16页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第13章 多线程(共24页).ppt 完整版精品java课件 Java基础入门教程 Java程序设计 第14章 socket网络编程(共24页).ppt
完整全套资源下载地址:https://download.csdn.net/download/qq_27595745/57256626 【完整课程列表】 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第10章 输入与输出(共38页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第11章 GUI图形用户界面设计(共129页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第12章 swing 组件(共59页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第13章 applet程序(共20页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第14章 多线程(共32页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第15章 数据库编程(共45页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第16章 网络编程(共33页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第1章 概述(共20页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第2章 java基础(共56页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第3章 流程控制(共41页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第4章 方法 函数(共26页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第5章 数组(共58页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第6章 类和对象(共50页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第7章 类的集成和多态机制(共40页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第8章 接口和包(共48页).ppt 推荐课程 完整版优质java教程 java精品教学课件 Java语言程序设计 第9章 异常处理(共26页).ppt
本书浅显易懂的介绍了JAVA线程相关的设计模式,通过程序范例和UML图示来一一解说,书中代码的重要部分加了标注以使读者更加容易理解,再加上图文并茂,对于初学者还是程序设计高手来说,这都是一本学习和认识JAVA设计模式的一本好书。(注意,本资源附带书中源代码可供参考) 多线程与并发处理是程序设计好坏优劣的重要课题,本书通过浅显易懂的文字与实例来介绍Java线程相关的设计模式概念,并且通过实际的Java程序范例和 UML图示来一一解说,书中在代码的重要部分加上标注使读者更加容易解读,再配合众多的说明图解,无论对于初学者还是程序设计高手来说,这都是一本学习和认识设计模式非常难得的好书。 书中包含Java线程的介绍导读、12个重要的线程设计模式和全书总结以及丰富的附录内容。第一章相关线程设计模式的介绍,都举一反三使读者学习更有效。最后附上练习问题,让读者可以温故而知新,能快速地吸收书中的精华,书中最后附上练习问题解答,方便读者学习验证。 目录 漫谈UML UML 类图 类和层次结构的关系 接口与实现 聚合 访问控制 类间的关联性 顺序图 处理流程和对象间的协调 时序图 Introduction 1 Java语言的线程 Java语言的线程 何谓线程 明为追踪处理流程,实则追踪线程 单线程程序 多线程程序 Thread类的run方法和start方法 线程的启动 线程的启动(1)——利用Thread类的子类 线程的启动(2)——利用Runnable接口 线程的暂时停止 线程的共享互斥 synchronized方法 synchronized阻挡 线程的协调 wait set——线程的休息室 wait方法——把线程放入wait set notify方法——从wait set拿出线程 notifyAll方法——从wait set拿出所有线程 wait、notify、notifyAll是Object类的方法 线程的状态移转 跟线程有关的其他话题 重点回顾 练习问题 Introduction 2 多线程程序的评量标准 多线程程序的评量标准 安全性——不损坏对象 生存性——进行必要的处理 复用性——可再利用类 性能——能快速、大量进行处理 评量标准的总结 重点回顾 练习问题 第1章 Single Threaded Execution——能通过这座桥的,只有一个人 第2章 Immutable——想破坏它也没办法 第3章 Guarded Suspension——要等到我准备好喔 第4章 Balking——不需要的话,就算了吧 第5章 Producer-Consumer——我来做,你来用 第6章 Read-Write Lock——大家想看就看吧,不过看的时候不能写喔 第7章 read-Per-Message——这个工作交给你了 第8章 Worker Thread——等到工作来,来了就工作 第9章 Future——先给您这张提货单 第10章 Two-Phase Termination——快把玩具收拾好,去睡觉吧 第11章 Thread-Specific Storage——每个线程的保管箱 第12章 Active Object——接受异步消息的主动对象 总结 多线程程序设计的模式语言 附录A 练习问题的解答 附录B Java的内存模型 附录C Java线程的优先级 附录D 线程相关的主要API 附录E 参考文献

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值