• 第16周作业


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

    1.代码

    time类
    import java.awt.*;
    import java.util.Date;
    
    public class Time extends Thread {
        Date date=null;
       public void run(){
           while (true){
               date =new Date();
               System.out.println(date);
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
       }
    }

    Test类
    
    public class Test {
        public static void main(String[] args) {
         Time time = new Time();
         time.start();
        }
    }

    2.运行结果

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

     1.代码

    Tset2类
    
    public class Test2 {
        public static void main(String[] args) {
            System.out.println("游戏开始 请输入一个0-100之间的数字:");
            Scanner reader = new Scanner(System.in);
            Thread a1 = new Thread();
            Thread game = new Thread(a1);
            game.start();
            try {
                Thread.sleep(100);
                for(int i=0;i<=10;i++) {
                    if (i == 10) {
                        System.out.println("GAME OVER!");
                        break;
                    }
                    int a2 = reader.nextInt();
                    if (a1.getId() > a2) {
                        System.out.println("数字偏小");
                        continue;
                    } else if (a1.getId() < a2) {
                        System.out.println("数字偏大");
                        continue;
                    } else if (a1.getId() == a2) {
                        System.out.println("你答对了!");
                        break;
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
        }
    }
    game类
    
    package qqq;
    
    import java.util.Random;
    
    public class Game implements Runnable {
        int number;
        public synchronized void run() {
            Random random= new Random();
    
            number=(int)(Math.random()*100);
        }
        public int getNum() {
            return number;
        }
        public void setNum(int num) {
            this.number=num;
        }
    
    }

    2.运行结果

  • 相关阅读:
    C语言开发框架、printf(day02)
    Linux C(day01)
    线程同步、信号量、system v IPC
    UDP、线程、mutex锁(day15)
    Socket编程(day14)
    共享内存、网络(day13)
    pause、jobs、setitimer(2)、system v ipc(day12)
    PIPE、SIGNAL(day11)
    环境变量、system(day10)
    进程(day09)
  • 原文地址:https://www.cnblogs.com/changheng/p/12080647.html
Copyright © 2020-2023  润新知