Java16周作业

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

/*使用Runnable接口使用类创建线程对象,重写run()方法**/

代码

1public class timetext { 2 3 4 public static void main(String[] args) { 5 Thread thread =new Thread(new time()); 6 thread.start(); 7 8 } 9 10} 11 12import java.util.Date; 13 14 15public class time implements Runnable { 16 17 public void run() { 18 Date date =null; 19 while(true){ 20 date=new Date(); 21 System.out.println(date); 22 try { 23 Thread.sleep(1000); 24 } catch (InterruptedException e) { 25 e.printStackTrace(); 26 } 27 } 28} 29 30}

  运行结果

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

代码

1public class Test { 2 3 4 public static void main(String[] args) { 5 game ga=new game(); 6 ga.rand.start(); 7 ga.input.start(); 8 9 } 10 11} 12 13import java.util.*; 14public class game implements Runnable { 15 Thread rand,input; 16 int inputnum,random,flag; 17 boolean a=false,b=false; 18 public game(){ 19 rand=new Thread(this); 20 input=new Thread(this); 21 } 22 23 public void run() { 24 while(true){ 25 compare(); 26 if(flag==3) 27 return; 28 } 29 } 30 public synchronized void compare(){ 31 if(Thread.currentThread()==rand&&b==false){ 32 random=(int)(Math.random()*100)+1; 33 System.out.println("猜数游戏开始!"); 34 a=true; 35 b=true; 36 } 37 if(Thread.currentThread()==rand){ 38 if(a==true){ 39 try { 40 wait(); 41 } catch (InterruptedException e) { 42 43 e.printStackTrace(); 44 } 45 } 46 if(inputnum<random){ 47 System.out.println("猜小了!请重猜!"); 48 flag=1; 49 } 50 else if(inputnum>random){ 51 System.out.println("猜大了!请重猜!"); 52 flag=2; 53 } 54 else if(inputnum==random){ 55 System.out.println("恭喜您猜对了!"); 56 flag=3; 57 } 58 a=true; 59 notifyAll(); 60 61 } 62 if(Thread.currentThread()==input){ 63 while(a==false){ 64 try { 65 wait(); 66 } catch (InterruptedException e) { 67 68 e.printStackTrace(); 69 } 70 } 71 if(flag<3){ 72 System.out.println("请输入您猜的数!"); 73 Scanner r=new Scanner(System.in); 74 inputnum=r.nextInt(); 75 } 76 a=false; 77 } 78 notifyAll(); 79 } 80 81}

  运行结果

点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

Java学习 Day01 多线程

Java学习Day01多线程Java多线程实现方式有2种1.继承Thread类,重写run方法案例测试类Thread01Javapackagetop.wanqq.thread;/@authorwanqq/publicclassThread01extendsThread@Overridepubli

java 多线程同步锁的使用 三个售票窗口同时出售20张票

packageThread;/三个售票窗口同时出售20张票程序分析:1.票数要使用同一个静态值2.为保证不会出现卖出同一个票数,要java多线程同步锁。设计思路:1.创建一个站台类Station,继承Thread,重写run方法,在run方法里面执行售票操作

一篇文章弄懂Java多线程基础和Java内存模型

文章目录一、多线程的生命周期及五种基本状态二、Java多线程的创建及启动1.继承Thread类,重写该类的run()方法2.通过实现Runnable接口创建线程类3.通过Callable和Future接口创建线程三、Java内存模型概念四、内存间的交互操作五、volatile和synchronized的

Java高并发编程四

_做个笔记,java线程常用的方法,耐心看完._编号方法说明1publicvoidstart()使该线程开始执行;Java虚拟机调用该线程的run方法。2publicvoidrun()如果该线程是使用独立的Runnable运行对象构造的,则调用该Runnable对象的run方法;否则,该方

Java面试系列

实现多线程的方式继承Thread类,重写run方法,调用start方法启动线程实现Runnable接口,重写run方法,调用start方法启动线程实现Callable接口,重写call方法,并用FutureTask包装,在newThread中传入FutureTask,然后调用start方

Java16周作业 - HelloWorld