running program is called a process, a process can contain multiple threads, processes can share resources, they share a storage space. Then, each thread to access the same data object at the same time, it may cause a conflict, the producer, the consumer, for example, will not appear in the queue of products, consumers get thrown queue products, and the real world the logic is not consistent. Using synchronized keyword ensures safe operation of the thread.
synchronized(obj){
.......
obj.wait()/notifyAll();//是数据对象而不是线程调用wait和notifyAll方法
}
When a thread (such as A thread) body of the run method of adding the above code, Description A thread must first obtain the data object's lock on the object to operation. A data object obj get this thread lock after its release before any other thread will not be able to manipulate this object, the reason for this, we can assume that other threads do not key to the lock. A thread obj.wait () method, it will release the object lock in its possession, A thread enters the blocked state, while A also does not have the power to get obj object, so that other threads can get this put the lock. obj.notifyAll () can wake up because of the object obj all threads are blocked, and allows them to have access to the power of the object, obj.notify () is a wake-up object obj blocked due to the first thread.
following procedure to imitate producers and consumers:
public class WaitAndNotify {
private static List<Double> queue;
public WaitAndNotify(){
queue = new ArrayList<Double>();
}
public void begin(){
Thread producer = new Thread(){
public void run(){
while(true){
synchronized(queue){
double time = 1.0d;
long startTime = System.currentTimeMillis();
if(System.currentTimeMillis()-startTime>=time){
startTime =System.currentTimeMillis();
for(int i=0;i<10;i++){
queue.add((Math.random()*10000));
}
queue.notifyAll();
}
}
}
}
};
producer.start();
Thread consumer = new Thread(){
public void run(){
while(true){
synchronized(queue){
while(queue.isEmpty()){
System.out.println("队列的长度为:"+queue.size());
try {
queue.wait();
} catch (InterruptedException ex) {
Logger.getLogger(WaitAndNotify.class.getName()).log(Level.SEVERE, null, ex);
}
}
double result = queue.remove(0);
System.out.println("成功从队列中取到数据!"+result);
}
}
}
};
consumer.start();
}
public static void main(String[] args){
WaitAndNotify obj = new WaitAndNotify();
queue.add(0.1231d);
obj.begin();
}
}
producer thread to the queue placed data, and calls out queue.notifyAll () to wake up all the blocked thread, consumer thread take data from the queue, when there is no data that thread will enter the blocked state, waiting chant wake .
没有评论:
发表评论