第16周作业

题目1:编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。

import java.awt.*;
import javax.swing.*;
import java.util.Date;
import java.awt.*;
class Time extends JFrame implements Runnable{//实现接口
Thread clockThread;
   JLabel jLabel=new JLabel();
   public Time()
   {
   Container con=this.getContentPane();
   con.add(new Drawtime());
   }
public void start(){
//该方法是类的方法,不是线程的方法
if(clockThread==null){
   clockThread=new Thread(this,"Clock");
   /*线程体是Clock对象本身,线程名字为"Clock"*/
   clockThread.start();//启动线程
}

public void run(){//run()方法中是线程执行的内容
    while(clockThread!=null){
    repaint();//刷新显示画面
    try{
       clockThread.sleep(1000);
       //睡眠1秒,即每隔1秒执行一次
    }
    catch(InterruptedException e){}
    }
}
public void stop(){
//该方法是类的方法,不是线程的方法
clockThread.stop();
clockThread=null; 
}
}
public class JFrameDemo 
{public static void main(String[] args)
{Time frame=new Time(); 
frame.setSize(500,300); 
frame.setVisible(true);                   //设置组件可见   
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //关闭容口,并结束程序的运行
frame.start();
frame.run();
frame.stop();
}
}
class Drawtime extends JPanel
{
public void paint(Graphics g){
   g.setColor(Color.red);
   Font font1=new Font("华文彩云",Font.ITALIC,60);
   g.setFont(font1);
Date now=new Date();//获得当前的时间对象
g.drawString(now.getHours()+":"+now.getMinutes()+":"+now.getSeconds(),140,140);
//显示当前时间

}

 题目2:编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)

import java.util.InputMismatchException;

import java.util.Scanner;
public class Main {

public static void main(String[] args) {

// 产生一个随机数

int number = (int) (Math.random() * 100) + 1;
// 加入count

int count = 0;
// 在这里加入最大值,和最小值

int max = 100;

int min = 1;
while (true) {

// 键盘录入数据

Scanner sc = new Scanner(System.in);

System.out.println("请输入你要猜的数据:(" + min + "~" + max + ")");

try {

count++;

int guessNumber = sc.nextInt();

// 判断

if (guessNumber > number) {

max = guessNumber;

System.out.println("你猜大了");

} else if (guessNumber < number) {

min = guessNumber;

System.out.println("你猜小了");

} else {

System.out.println("恭喜你,花了" + count + "次就猜中了");

// 问是否继续

System.out.println("请问还要继续吗?(yes)");

sc = new Scanner(System.in);

String str = sc.nextLine();

if ("yes".equals(str)) {

// 重写赋值随机数

number = (int) (Math.random() * 100) + 1;

count = 0;

max = 100;

min = 1;

} else {

break;

}

}

} catch (InputMismatchException e) {

System.out.println("你输入的数据有误");

}

}

}

}

posted @ 2019-12-17 21:21  jackquick  阅读(167)  评论(0编辑  收藏  举报