通过管理自身,您可能意味着管理其锁的同步并根据某些条件遵守其实例变量的边界。
public class ThreadClass implements Runnable {
public void run() {
// .. Does some arbitrary work
synchronized (this) {
while (! aCondition) { // have it wait until something signals it to
// contine exection.
this.wait();
}
}
/* Reset the aCondition var to its old value to allow other threads to
enter waiting state
Continues to do more work.
Finished whatever it needed to do. Signal all other threads of this
object type to continue their work.*/
synchronized (this) {
this.notifyAll();
}
}
}
您还应该查看Condition界面。除了使用 java.util.concurrent 类之外,它似乎具有完全相同的要求。有一个BoundedBuffer的例子。
请参阅下面的生产者消费者示例。它具有相同的等待/通知模板。可用标志声明为 volatile,以便可以对其执行线程安全读取和写入。
public class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class CubbyHole {
private int contents;
private volatile boolean available = false;
public int get() {
synchronized (this) {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
available = false;
synchronized (this) {
notifyAll();
}
return contents;
}
public void put(int value) {
synchronized (this) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
available = true;
contents = value;
synchronized (this) {
notifyAll();
}
}
}
class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
private Integer takeSum = new Integer(0);
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public Integer getTakeSum() {
return takeSum;
}
public void run() {
int value = 0;
for (int i = 0; i < 100; i++) {
value = cubbyhole.get();
takeSum+=value;
}
System.out.println("Take Sum for Consumer: " + number + " is "
+ takeSum);
}
}
class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
private Integer putSum = new Integer(0);
public Integer getPutSum() {
return putSum;
}
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 100; i++) {
int rnd = (int) (Math.random() * 10);
cubbyhole.put(rnd);
putSum+=rnd;
try {
sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
}
}
System.out.println("Put Sum for Producer: " + number + " is " + putSum);
}
}