不会。需要等到synchronized里面的代码块执行玩才会在释放锁。
案例 : 工厂共需要生产30个产品(产品1~产品30), 生产者每生产5个产品就会通知消费者来消费,等到5件产品消费完了然后再通知生产者继续生产,直到30个产品都被生产和消费后结束。生产一个产生默认需要200ms, 消费一个产品需要100毫秒。
package FactoryAndCustomer;
import java.util.LinkedList;
public class Factory {
private LinkedList<Product> list = new LinkedList<>();
private Factory() {
super();
}
public static Factory getInstance() {
return new Factory();
}
public synchronized void createBatchProduct() throws InterruptedException {
for (int i = 0; i <= 30 ; i++) {
createOne(new Product(i));
}
}
public void createOne(Product product) throws InterruptedException {
while(list.size() == 5) {
this.wait();
}
list.add(product);
Thread.sleep(200);
System.out.println(Thread.currentThread().getName()+"成功生产出"+product);
this.notifyAll();
}
public synchronized void consumeBatchProduct() throws InterruptedException {
for (int i = 0; i <= 30 ; i++) {
consumeOne();
}
}
public void consumeOne() throws InterruptedException {
while(list.isEmpty()) {
this.wait();
}
Product product = list.removeLast();
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+"成功消费"+product);
this.notifyAll();
}
}
package FactoryAndCustomer;
public class Product {
private int id;
public Product(int id) {
super();
this.id = id;
}
@Override
public String toString() {
return id + "号产品";
}
}
package FactoryAndCustomer;
public class Producter extends Thread{
private Factory factory;
public Producter(String name, Factory factory) {
super(name);
this.factory = factory;
}
@Override
public void run() {
try {
factory.createBatchProduct();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package FactoryAndCustomer;
public class Customer extends Thread{
private Factory factory;
public Customer(String name, Factory factory) {
super(name);
this.factory = factory;
}
@Override
public void run() {
try {
factory.consumeBatchProduct();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package FactoryAndCustomer;
public class testMain {
public static void main(String[] args) {
Factory factory = Factory.getInstance();
Producter producter = new Producter("生产者", factory);
Customer customer = new Customer("消费者", factory);
producter.start();
customer.start();
}
}