我按照教程上,写的,发现可以编译,但无法输出
- //线程间通信,存资源和取资源
- class Resource { //资源
- private String a;
- private String b;
- private boolean flag = false;
- public synchronized void setS(String s1,String s2) {
- if(flag) {
- try {wait();}catch(Exception e) {}
- this.a = s1;
- this.b = s2;
- flag = true;
- notify();
- }
- }
- public synchronized void getS() {
- if(!flag) {
- try {wait();}catch(Exception e) {}
- System.out.println(a + " love " + b);
- flag = false;
- notify();
- }
- }
- }
- class Input implements Runnable { //存资源线程
- private Resource r;
- Input(Resource r) {
- this.r = r;
- }
- public void run() {
- int i = 0;
- while(true) {
-
- if(i == 0) {
- r.setS("abc","cba");
- }else {
- r.setS("cba","abc");
- }
- i = (i + 1) % 2;
- }
- }
- }
- class Output implements Runnable { //取资源线程
- private Resource r;
- Output(Resource r) {
- this.r = r;
- }
- public void run() {
- while(true) {
- r.getS();
- }
- }
- }
- class ThreadCommunication {
- public static void main(String[] args) {
- Resource r = new Resource();
- new Thread(new Input(r)).start(); //开启存资源线程
- new Thread(new Output(r)).start(); //开启取资源线程
- }
- }
复制代码
|
|