public Object getSth(){
if(vector.size()==0) wait();
synchronize(vector){
Object o = vector.firstElement();
vector.removeElementAt(0);
return o;
}
}public void returnSth(Object sth){
synchronize(vector){
vector.add(sth);
notifyAll();
}
}
if(vector.size()==0) wait();
synchronize(vector){
Object o = vector.firstElement();
vector.removeElementAt(0);
return o;
}
}public void returnSth(Object sth){
synchronize(vector){
vector.add(sth);
notifyAll();
}
}
解决方案 »
- 这个程序结果怎么是乱码?
- jdbc update的问题
- 怎样用java语句实现 类似QQ表情的弹出窗口?
- package会影响Jar打包吗?
- 人民币大小写转换问题
- .mdb文件存放位置
- JAVA怎样计算两个日期之间的差
- 过中秋节费用调查,请问你们公司给多少费用啊!
- 一个jdbc的问题,问了好多人都不知道怎么解决,大家来给看看(在线等待答案)
- 关于垃圾收集器的一个问题
- 急!急!请教:我把applet中的.class文件放在和网页同一目录下,然后用<applet width="487" height="273" code="pic.class">引用,为什么浏览网页时他说class pic not found?
- 想考SCJP,请各位高手接指点,哪本书比较好!!
extends Thread
{
public static class Resource
{
public static Resource resource = new Resource(); //共享资源
boolean resourceInUse = false;
int count = 0;
public void setCount( int count ){ this.count = count; }
public int getCount(){ return count; }
public Resource get()
{
while( resourceInUse ) //*** 试试看用if会如何。
{
try
{
synchronized(this)
{
System.out.println( Thread.currentThread().getName() + " is waiting..." );
wait();
}
}
catch( Exception e )
{
e.printStackTrace();
}
}
resourceInUse = true;
return this;
}
public void ret()
{
try
{
resourceInUse = false;
synchronized(this)
{
System.out.println( Thread.currentThread().getName() + " notified all." );
notifyAll();
}
}
catch( Exception e )
{
e.printStackTrace();
}
}
public static Resource getResource()
{
return resource.get();
}
public static void returnResource()
{
resource.ret();
}
}; public void run()
{
//取得,计算,设置
Resource r = Resource.getResource();
System.out.println( getName() + ": add 10" );
int rc = r.getCount();
try
{
sleep( 100 );
}
catch( Exception e )
{
e.printStackTrace();
}
r.setCount( rc + 10 );
Resource.returnResource();
}
public static void main( String args[] )
throws Exception
{
int n = Integer.valueOf(args[0]).intValue();
System.out.println( "Before " + n + " threads using the resource. count = " + Resource.getResource().getCount() );
Resource.returnResource();
SyncTest tests[] = new SyncTest[n];
for( int i = 0; i < n; i++ )
tests[i] = new SyncTest();
for( int i = 0; i < n; i++ )
tests[i].start();
for( int i = 0; i < n; i++ )
tests[i].join();
System.out.println( "After " + n + " threads used the resource. count = " + Resource.getResource().getCount() );
Resource.returnResource();
}
}
while应当和notifyAll配合。
notify,我想用if就可以了。