两个线程模拟猜数字
2017-12-13 13:21
351 查看
1.一个线程随机生成数字,以及判断是否才对
2.另一个线程接受用户的收入数字
2.另一个线程接受用户的收入数字
package www.whf.test2; import java.util.Scanner; public class Test2 { static Thread t1 = null; public static void main(String[] args) { t1 = new Thread(() -> { int i = 1; int num0; while (true) { System.out.println("第" + (i++) + "轮"); num0 = ((int) ((Math.random() * 10))); System.out.println("请猜"); while (true) { synchronized (t1) { try { t1.wait(); } catch (InterruptedException e1) { e1.printStackTrace(); } } // System.out.println("数字"+num0); if (num0 == num.getnum()) { System.out.println("猜中了"); break; } else if (num0 > num.getnum()) { System.out.println("猜小了"); } else { System.out.println("猜大了"); } } } }); t1.start(); new Thread(() -> { Scanner sc = new Scanner(System.in); while (true) { num.setnum(sc.nextInt()); System.out.println("我猜是" + num.getnum()); synchronized (t1) { t1.notifyAll(); } } }).start(); } static class num { static int num; static boolean flag = true; public static synchronized void setnum(int num) { Test2.num.num = num; } public static synchronized int getnum() { return num; } } }
相关文章推荐
- 使用两个队列实现一个栈
- Mysql两个查询结果相加?错误:Every derived table must have its own alias
- 第十一周OJ(5)求两个整数的最大公约数和最小公倍数
- 2-12. 两个有序链表序列的交集
- 两个for循环例子
- 两个文本框都输入数字后只要焦点一失去,在第三个文本框中就自动计算出前两个的和或者积
- 关于ReentrantReadWriteLock两个问题及解决心得(转)
- 《arraycopy()方法复制两个数组》
- Marshal类的两个方法StructureToPtr和PtrToStructure实现序列化
- 【OPNET学习系列文章之2】两个固定节点通信
- 链表——两个有序链表序列的合并
- Nodejs GET 方法与POST 方法提交表单两个参数
- (java)求两个排序数组(升序)中第K小的数
- 定义Car类,包含两个字段:name和price; (2)在Main方法中,使用Array.Sort方法对Car对象数组根据姓名和价格排序。
- Android(5)— Mono For Android 两个功能型外包
- 面试题7:用两个栈实现队列
- 隐藏桌面‘回收站’的两个方法
- 两个窗体(form)间传递参数
- php数组函数序列之array_intersect() 返回两个或多个数组的交集数组
- 大数相加,两个大数。