当前位置: 技术问答>java相关
大家帮忙看一个线程的小例子。
来源: 互联网 发布时间:2015-09-28
本文导语: package mythread; /** * Title: * Description: * Copyright: Copyright (c) 2002 * Company: * @author unascribed * @version 1.0 */ class Cubby { private int number; private boolean avaliable=false; public synchronized void get(){ ...
package mythread;
/**
*
*
*
*
* @author unascribed
* @version 1.0
*/
class Cubby {
private int number;
private boolean avaliable=false;
public synchronized void get(){
if(avaliable==false){
try{
wait();
}
catch(InterruptedException e){
System.out.println("wrong");
}
}
avaliable=false;
notify();
System.out.println("the client get:"+number);
}
public synchronized void put(int n){
if(avaliable==true){
try{
wait();
}
catch(InterruptedException e){
System.out.println("wrong!");
}
avaliable=true;
number=n;
notify();
System.out.println("the server put:"+number);
}
}
}
------------------------------------------------------------
package mythread;
/**
*
*
*
*
* @author unascribed
* @version 1.0
*/
class Server extends Thread{
private Cubby cubby;
Server(Cubby cubby){
this.cubby=cubby;
}
public void run(){
for(int i=0;i
/**
*
Title:
*
Description:
*
Copyright: Copyright (c) 2002
*
Company:
* @author unascribed
* @version 1.0
*/
class Cubby {
private int number;
private boolean avaliable=false;
public synchronized void get(){
if(avaliable==false){
try{
wait();
}
catch(InterruptedException e){
System.out.println("wrong");
}
}
avaliable=false;
notify();
System.out.println("the client get:"+number);
}
public synchronized void put(int n){
if(avaliable==true){
try{
wait();
}
catch(InterruptedException e){
System.out.println("wrong!");
}
avaliable=true;
number=n;
notify();
System.out.println("the server put:"+number);
}
}
}
------------------------------------------------------------
package mythread;
/**
*
Title:
*
Description:
*
Copyright: Copyright (c) 2002
*
Company:
* @author unascribed
* @version 1.0
*/
class Server extends Thread{
private Cubby cubby;
Server(Cubby cubby){
this.cubby=cubby;
}
public void run(){
for(int i=0;i