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

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

代码

public class timetext {

	public static void main(String[] args) {
Thread thread =new Thread(new time());
thread.start(); } }

  

import java.util.Date;

public class time implements Runnable {

	public void run() {
Date date =null;
while(true){
date=new Date();
System.out.println(date);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} }

  运行结果

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

代码

public class Test {

	public static void main(String[] args) {
game ga=new game();
ga.rand.start();
ga.input.start(); } }

  

import java.util.*;
public class game implements Runnable {
Thread rand,input;
int inputnum,random,flag;
boolean a=false,b=false;
public game(){
rand=new Thread(this);
input=new Thread(this);
} public void run() {
while(true){
compare();
if(flag==3)
return;
}
}
public synchronized void compare(){
if(Thread.currentThread()==rand&&b==false){
random=(int)(Math.random()*100)+1;
System.out.println("猜数游戏开始!");
a=true;
b=true;
}
if(Thread.currentThread()==rand){
if(a==true){
try {
wait();
} catch (InterruptedException e) { e.printStackTrace();
}
}
if(inputnum<random){
System.out.println("猜小了!请重猜!");
flag=1;
}
else if(inputnum>random){
System.out.println("猜大了!请重猜!");
flag=2;
}
else if(inputnum==random){
System.out.println("恭喜您猜对了!");
flag=3;
}
a=true;
notifyAll(); }
if(Thread.currentThread()==input){
while(a==false){
try {
wait();
} catch (InterruptedException e) { e.printStackTrace();
}
}
if(flag<3){
System.out.println("请输入您猜的数!");
Scanner r=new Scanner(System.in);
inputnum=r.nextInt();
}
a=false;
}
notifyAll();
} }

  运行结果

最新文章

  1. C#进阶系列——MEF实现设计上的“松耦合”(终结篇:面向接口编程)
  2. UVa 221城市正视图(离散化)
  3. android中自定义的dialog中的EditText无法弹出输入法解决方案
  4. 理解 Memory barrier
  5. IIS 7.5站点配置
  6. windows修改mysql默认字符集不成功
  7. ubuntu用户及用户组文件信息
  8. java-map-EnumMap
  9. [Unity3D]脚本中Start()和Awake()的差别
  10. TodoList开发笔记 – Part Ⅲ
  11. Python之数据结构基础
  12. drupal 8 之 captcha模块
  13. OSGI打安装包步骤(底包制作)
  14. 学习RabbitMQ(三):AMQP事务机制
  15. 机器学习(Machine Learning)算法总结-决策树
  16. let的使用 优先于闭包
  17. Linux CentOS7.5上二进制安装MySQL5.7.23
  18. Mysql 调优2个语句
  19. ajax传递的参数服务器端接受不到的原因
  20. npm和cnpm(windows)安装步骤

热门文章

  1. wordpress防止垃圾邮件方法
  2. win10 .net framework 3.5 离线安装 不需要外网
  3. [转帖]pidstat 命令详解
  4. MyBatis系列(二) MyBatis接口绑定与多参数传递
  5. 实验代码:const* 和 const&amp;
  6. altermanager使用报错
  7. Vue学习之组件切换及父子组件小结(八)
  8. IOS之NSString NSData char 相互转换
  9. Flask的上下文管理
  10. pycharm动态设置字体放大缩小