62,620
社区成员
发帖
与我相关
我的任务
分享package syn4;
/**
* 测试类
*/
public class TestAccount {
public static void main(String[] args) {
Accout a = new Accout();
StudentThread s = new StudentThread(a);
GenearchThread g = new GenearchThread(a);
}
}
package syn4;
/**
* 模拟学生线程
*/
public class StudentThread extends Thread {
Accout a;
public StudentThread(Accout a){
this.a = a;
start();
}
public void run(){
try{
while(true){
Thread.sleep(2000);
a.getMoney(); //取钱
}
}catch(Exception e){}
}
}
package syn4;
/**
* 家长线程
*/
public class GenearchThread extends Thread {
Accout a;
public GenearchThread(Accout a){
this.a = a;
start();
}
public void run(){
try{
while(true){
Thread.sleep(12000);
a.saveMoney(); //存钱
}
}catch(Exception e){}
}
}
package syn4;
/**
* 银行账户
*/
public class Accout {
int money = 0;
/**
* 取钱
* 如果账户没钱则等待,否则取出所有钱提醒存钱
*/
public synchronized void getMoney(){
System.out.println("准备取钱!");
try{
if(money == 0){
wait(); //等待
}
//取所有钱
System.out.println("剩余:" + money);
money -= 50;
//提醒存钱
notify();
}catch(Exception e){}
}
/**
* 存钱
* 如果有钱则等待,否则存入200提醒取钱
*/
public synchronized void saveMoney(){
System.out.println("准备存钱!");
try{
if(money != 0){
wait(); //等待
}
//取所有钱
money = 200;
System.out.println("存入:" + money);
//提醒存钱
notify();
}catch(Exception e){}
}
}Threads can be in one of six states:
•New
• Runnable
• Blocked
•Waiting
• Timed waiting
•Terminated
Once you invoke the start method, the thread is in the runnable state. A runnable
thread may or may not actually be running. It is up to the operating system to give
the thread time to run. (The Java specification does not call this a separate state,
though. A running thread is still in the runnable state.) [/quote]
我给的例子中,runnable 状态分开了。runnable and running.
"Once you invoke the start method, the thread is in the runnable state. A runnable
thread may or may not actually be running."
class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}

Threads can be in one of six states:
•New
• Runnable
• Blocked
•Waiting
• Timed waiting
•Terminated
Once you invoke the start method, the thread is in the runnable state. A runnable
thread may or may not actually be running. It is up to the operating system to give
the thread time to run. (The Java specification does not call this a separate state,
though. A running thread is still in the runnable state.)