请问各位大侠,为什么wite()的异,不能抛出,只能try catch?
- package com.itheima;
- /*
- * 一个资源用来存储数据
- * 两个线程,一个存数据,一个去数据
- */
- class Resource {
- private String name;
- private String sax;
- boolean flag = false;
- public synchronized void set(String name, String sax) {
- if(flag) {
-
- //为什么这里的wait()异常不能抛出,只能try catch???
- try{
- this.wait();
- }
- catch(Exception e) {
- System.out.println(e.toString());
- }
- }
- this.name = name;
- this.sax = sax;
- flag = true;
- this.notify();
- }
- public synchronized void out() {
- if(!flag) {
- try{
- this.wait();
- }
- catch(Exception e) {
- System.out.println(e.toString());
- }
- }
- System.out.println(name+". . ."+sax);
- flag = false;
- this.notify();
- }
- }
- class Input implements Runnable {
- private Resource res;
- //创建对象时传入资源
- Input(Resource res) {
- this.res = res;
- }
- public void run() {
- int x = 0;
- while(true) {
- if(x==0)
- res.set("mike", "man");
- else
- res.set("丽丽", "女");
- x = (x+1)%2;
- }
- }
- }
- class Outpt implements Runnable {
- private Resource res;
- Outpt(Resource res) {
- this.res = res;
- }
- public void run() {
- while(true) {
- res.out();
- }
- }
- }
- public class Test {
- public static void main(String[] arge) {
- Resource res = new Resource();
-
- new Thread(new Input(res)).start();
- new Thread(new Outpt(res)).start();
- }
- }
复制代码
|