两个面试题(关于notify和wait)

1.一个容器,两个线程,程一往线程加东西。程二等待,等加到5个时阻塞成一,

2.两个消费线程,十个生产线程,容器里最多不超过十个。

public class Container4 {

public Listlist =new ArrayList();

public int size (){

return  list.size();

}

public void add(Object o){

list.add(o);

}

public static void main(String[] args)throws IOException {

Container4 c4 =new Container4();

Object lock =new Object();

Thread t =new Thread();

ServerSocket server =new ServerSocket();

Socket accept = server.accept();

new Thread(()->{

synchronized (lock){

if (c4.size()!=5){

try {

lock.wait();

}catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("Thread2执行完毕");

lock.notify();

}

},"thread2").start();

new Thread(()->{

synchronized (lock){

for (int i =0;i<10;i++){

c4.add(new Object());

System.out.println("add"+i);

if (c4.size()==5) {

lock.notify();

try {

lock.wait();

}catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

}).start();

}

}


public class Continer5 {

public Listlist =new ArrayList();

public int size (){

return  list.size();

}

public void add(Object o){

list.add(o);

}

public static void main(String[] args)throws IOException {

Continer5 c4 =new Continer5();

CountDownLatch latch =new CountDownLatch(1);

new Thread(()->{

if (c4.size()!=5){

try {

latch.await();

}catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("Thread2执行完毕");

},"thread2").start();

new Thread(()->{

for (int i =0;i<10;i++){

c4.add(new Object());

System.out.println("add"+i);

if (c4.size()==5) {

latch.countDown();

}

}

}).start();

}

}


public class Continer6 {

public LinkedListlist =new LinkedList();

int max =10;

int count =0;

public int size (){

return  list.size();

}

synchronized  void put(Object o)throws InterruptedException {

while (list.size()==max){

this.wait();

}

list.add(o);

++count;

this.notifyAll();

}

synchronized Object get()throws InterruptedException {

while (list.size()==0){

this.wait();

}

Object o =list.removeFirst();

--count;

return o;

}

public static void main(String[] args)throws InterruptedException {

Continer6 continer6 =new Continer6();

for(int i=0;i<100;i++){

new Thread(()->{

try {

System.out.println(continer6.get());

}catch (InterruptedException e) {

e.printStackTrace();

}

},"c"+i).start();

}

TimeUnit.SECONDS.sleep(2);

}

}

你可能感兴趣的:(两个面试题(关于notify和wait))