Java上机实验 多线程

目录

  • 实验1 键盘的操作练习
  • 实验2 双线程猜字
  • 实验3 汉字打字练习
  • 实验4 月球围绕地球

实验1 键盘的操作练习

TypeKey.java

public class TypeKey {
 public static void main(String args[]){
  System.out.println("键盘练习(输入#结束程序)");
  System.out.println("输入显示的字母(回车)\n");
  Letter letter;
  letter=new Letter();
  GiveLetterThread giveChar;
  InputLetterThread typeChar;
  giveChar=new GiveLetterThread();//创建线程giveChar
  giveChar.setLetter(letter);
  giveChar.setSleepLength(3200);
  typeChar=new InputLetterThread();//创建线程typeChar
  typeChar.setLetter(letter);
  giveChar.start();
  typeChar.start();
 }
}

Letter.java

public class Letter {
 char c='\0';
 public void setChar(char c){
  this.c=c;
 }
 public char getChar(){
  return c;
 }
}

GiveLetterThread.java

public class GiveLetterThread extends Thread {
 Letter letter;
 char startChar='a',endChar='z';
 int sleepLength=5000;
 public void setLetter(Letter letter){
  this.letter=letter;
 }
 public void setSleepLength(int n){
  sleepLength=n;
 }
 public void run(){
  char c=startChar;
  while(true){
   letter.setChar(c);
   System.out.printf("显示的字符:%c\n",letter.getChar());
   try{
    Thread.sleep(sleepLength);//调用sleep方法使得线程中断sleepLength毫秒
   }
   catch (InterruptedException e) {}
   c=(char)(c+1);
   if(c>endChar)
    c=startChar;
  }
 }
}

InputLetterThread.java

import java.awt.*;
import java.util.*;
public class InputLetterThread extends Thread {
 Scanner reader;
 Letter letter;
 int score=0;
 InputLetterThread(){
  reader=new Scanner(System.in);
 }
 public void setLetter(Letter letter){
  this.letter=letter;
 }
 public void run(){
  while(true){
   String str=reader.nextLine();
   char c=str.charAt(0);
   if(c==letter.getChar()){
    score++;
    System.out.printf("\t\t输入对了,目前分数%d\n",score);
   }
   else{
    System.out.printf("\t\t输入错了,目前分数%d\n",score);
   }
   if(c=='#') 
    System.exit(0);
  }
 }
}

实验2 双线程猜字

TwoThreadGuessNumber.java

public class TwoThreadGuessNumber {
 public static void main(String args[]){
  Number number=new Number();
  number.giveNumberThread.start();
  number.guessNumberThread.start();
 }
}

Number.java

public class Number implements Runnable {
 final int SMALLER=-1,LARGER=1,SUCCESS=8;
 int realNumber,guessNumber,min=0,max=100,message=SMALLER;
 boolean pleaseGuess=false,isGiveNumber=false;
 Thread giveNumberThread,guessNumberThread;
 Number(){
  giveNumberThread=new Thread(this);
  guessNumberThread=new Thread(this);
 }
 public void run() {
  for(int count=1;true;count++){
   setMessage(count);
   if(message==SUCCESS)
    return;
  }
 }
 public synchronized void setMessage(int count){
  if(Thread.currentThread()==giveNumberThread&&isGiveNumber==false){
   realNumber=(int)(Math.random()*100)+1;
   System.out.println("随机给你安排一个1至100之间的数,猜猜是多少?");
   isGiveNumber=true;
   pleaseGuess=true;
  }
  if(Thread.currentThread()==giveNumberThread){
   while(pleaseGuess==true)
    try{
     wait();
    }
    catch(InterruptedException e){}
   if(realNumber>guessNumber){
    message=SMALLER;
    System.out.println("你猜小了");
   }
   else if(realNumber>guessNumber){
    message=SMALLER;
    System.out.println("你猜大了");
   }
   else{
    message=SUCCESS;
    System.out.println("恭喜,你猜对了");
   }
   pleaseGuess=true;
  }
  if(Thread.currentThread()==guessNumberThread&&isGiveNumber==true){
   while(pleaseGuess==false)
    try{
     wait();
    }
    catch(InterruptedException e){}
    if(message==SMALLER){
     min=guessNumber;
     guessNumber=(min+max)/2;
     System.out.println("我第"+count+"次猜这个数是:"+guessNumber);
    }
    else if(message==LARGER){
     max=guessNumber;
     guessNumber=(min+max)/2;
     System.out.println("我第"+count+"次猜这个数是:"+guessNumber);
    }
    pleaseGuess=false;
  }
  notifyAll();
 }
}

实验3 汉字打字练习

ThreadWordMainClass.java

public class ThreadWordMainClass{  
 public static void main(String args[]){
       new ThreadFrame().setTitle("汉字打字练习");
   }
}

WordThread.java

import javax.swing.*;
public class WordThread extends Thread{
 char word;
 int startPosition =19968; //Unicode 表的19968 ~ 32320位上的汉字
 int endPosition = 32320;
 JTextField showWord;
 int sleepLength = 6000;
 public void setJTextField(JTextField t) {
  showWord = t;
  showWord.setEditable (false);
 }
 public void setSleepLength(int n) {
  sleepLength = n;
 }
 public void run() {
  int k=startPosition;
  while(true) {
   word= (char)k;
   showWord. setText (""+word) ; 
   try{ sleep(sleepLength);//调用sleep方法使得线程中断sleepLength毫秒
   }
   catch (InterruptedException e) {}
   k++;
  if (k>=endPosition)
   k=startPosition; 
  }
 }
}

ThreadFrame.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ThreadFrame extends JFrame implements ActionListener {
 JTextField showWord;
 JButton button;
 JTextField inputText, showScore;
 WordThread giveWord;//用WordThread声明一个giveWord线程对象
 int score=0;
 ThreadFrame() {
  showWord = new JTextField(6) ;
  showWord. setFont (new Font ("", Font . BOLD, 72)) ;
  showWord. setHorizontalAlignment (JTextField.CENTER ) ;
  giveWord=new WordThread();//创建giveWord线程
  giveWord.setJTextField (showWord) ;
  giveWord.setSleepLength (5000) ; 
  button=new JButton("开 始") ;
  inputText = new JTextField(10) ;
  showScore = new JTextField(5) ;
  showScore .setEditable (false) ;
  button. addActionListener (this) ;
  inputText . addActionListener (this) ;
  add (button, BorderLayout . NORTH) ;
  add ( showWord, BorderLayout . CENTER) ;
  JPanel southP=new JPanel () ;
  southP.add (new JLabel ("输入汉字(回车) :"));
  southP.add (inputText) ;
  southP.add (showScore) ;
  add(southP, BorderLayout . SOUTH) ;
  setBounds (100, 100, 350, 180) ;
  setVisible(true) ;
  validate() ;
  setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
 }
 public void actionPerformed(ActionEvent e) {
  if (e. getSource ()==button) {
   if(!(giveWord. isAlive())) {
    giveWord=new WordThread();//创建giveWord
    giveWord.setJTextField (showWord);
    giveWord.setSleepLength (5000);
   }
   try {
    giveWord.start();//giveWord调用start()方法
   }
   catch (Exception exe) {}
   }
  else if (e.getSource ()==inputText) {
   if (inputText. getText () .equals (showWord.getText()))
    score++ ;
   showScore.setText ("得分:"+score) ;
   inputText.setText (null) ;
  }
 }
}

实验4 月球围绕地球

MainClass.java

import javax. swing.*;
public class MainClass {
 public static void main(String args[]) {
  Sky sky= new Sky() ;
  JFrame frame = new JFrame() ;
  frame.add(sky);
  frame.setSize (500, 500) ;
  frame.setVisible(true) ;
  frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;
  frame.getContentPane().setBackground(java.awt.Color.white) ;
 }
}

Earth.java

import java.awt.*;
import javax . swing.*;
import java.awt.event. *;
public class Earth extends JLabel implements ActionListener {
 JLabel moon;//显示月亮的外观
 Timer timer;
 double pointX[] =new double [360],pointY[]=new double[360] ;
 int w=200, h=200, i=0;
 Earth(){
  setLayout (new FlowLayout()) ;
  setPreferredSize (new Dimension(w,h)) ;
  timer=new Timer(20,this);//创建timer,振铃间隔是20毫秒当前Earth对象为其监视器
  setIcon(new ImageIcon("earth.jpg"));
  setHorizontalAlignment(SwingConstants.CENTER) ;
  moon=new JLabel (new ImageIcon ("moon.jpg"),SwingConstants.CENTER) ;
  add (moon) ;
  moon. setPreferredSize (new Dimension(60,60) ) ;
  pointX[0]=0;
  pointY[0]=h/2;
  double angle=1*Math.PI/180;//刻度为1度
  for(int i=0;i<359;i++){ //计算出数组中 各个元素的值
   pointX[i+1]=pointX[i]*Math.cos(angle)-Math.sin(angle)*pointY[i];
   pointY[i+1]=pointY[i]*Math.cos(angle)+pointX[i]*Math.sin(angle);
  }
  for(int i=0;i<360;i++) {
   pointX[i]=0.8*pointX[i]+w/2; //坐标缩放, 平移
   pointY[i]=0.8*pointY[i] +h/2;
  }
  timer.start();
 }
 public void actionPerformed (ActionEvent e) {
  i=(i+1)%360;
  moon.setLocation( (int)pointX[i]-30, (int)pointY[i]-30) ;
 }
}

Sky.java

import java.awt. *;
import javax. swing.*;
import java.awt.event. *;
public class Sky extends JLabel implements ActionListener {
 Earth earth;
 Timer timer;
 double pointX[]=new double[360],pointY[]=new double [360];
 int w=400,h=400,i=0;
 Sky(){ 
  setLayout (new FlowLayout()) ;
  timer=new Timer(100,this);//创建timer,振铃间隔是100毫秒当前Sky对象为其监视器.
  setPreferredSize(new Dimension(w,h));
  earth=new Earth() ;
  add(earth);
  earth. setPreferredSize (new Dimension (200, 200) ) ;
  pointX[0]=0;
  pointY[0]=h/2;
  double angle=1*Math.PI/180; //刻度为1度
  for(int i=0;i<359;i++) {//计算出数组中各个元素的值
   pointX[i+1]=pointX[i] *Math.cos(angle)-Math.sin(angle)*pointY[i];
   pointY[i+1]=pointY[i] *Math.cos(angle)+pointX[i]*Math.sin(angle);
  }
  for (int i=0;i<360;i++) {
   pointX[i]=0.5*pointX[i]+w/2; //坐标缩放、 平移
   pointY[i]=0.5*pointY[i] +h/2;
  }
  timer.start () ;
 }
 public void actionPerformed (ActionEvent e) {
  i=(i+1)%360;
  earth.setLocation((int)pointX[i]-100,(int)pointY[i]-100);
 }
}

ZZU_CZZ/2020/5_27/22:49

你可能感兴趣的:(上机实验,java,多线程)