Java thread entry - synchronization of thread

xiaoxiao2021-03-06  97

// You can try to remove the following keyword Synchronized.

Public class cubbyhole {

PRIVATE INT CONTENTS;

Private boolean available = false;

Public synchronized int GET () {

While (available == false) {

Try {

Wait ();

} catch (interruptedexception e) {

}

}

Available = false;

NotifyAll ();

Return Contents;

}

Public Synchronized Void Put (int value) {

While (Available == True) {

Try {

Wait ();

} catch (interruptedexception e) {

}

}

CONTENTS = VALUE;

Available = True;

NotifyAll ();

}

}

Public class producer extends thread {

Private cubbyhole cubbyhole;

PRIVATE INT NUMBER;

Public product (cubbyhole c, int number) {

Cubbyhole = C;

THIS.NUMBER = NUMBER;

}

Public void run () {

For (int i = 0; i <10; i ) {

Cubbyhole.put (i);

System.out.println ("Producer #" this.Number "PUT:" i);

Try {

Sleep ((int) (Math.random () * 100));

} catch (interruptedexception e) {

}

}

}

}

Public class consumer extends thread {

Private cubbyhole cubbyhole;

PRIVATE INT NUMBER;

Public consumer (cubbyhole c, int number) {

Cubbyhole = C;

THIS.NUMBER = NUMBER;

}

Public void run () {

INT value = 0;

For (int i = 0; i <10; i ) {

Value = cubbyhole.get ();

System.out.println ("Consumer #" this.Number "got:" value);

}

}

}

Public class producerconsumertest {

Public static void main (String [] args) {

Cubbyhole c = new cubbyhole ();

Producter P1 = New Producter (C, 1);

Consumer C1 = New Consumer (C, 1);

p1.start ();

C1.Start ();

}

}

转载请注明原文地址:https://www.9cbs.com/read-105025.html

New Post(0)