











Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!












public class
ThreadExampleMain
public static void
main(String[] args) {
Thread myThread =
new
ThreadExample(“my data”);
myThread.start();System.out.println(“I am the main thread”); } }
RunnableExample
extends
SomeClass
implements
Runnable
private
String data;
public
RunnableExample(String data) { this
.data = data;
} public void
run() {
System.out.println(“I am a thread”);System.out.println(“I was given an argument : “ + data); } }
-^
-^
-^
-^
-^
-^
-^
-^
-^
-^
-^
-^
-^
Producer
extends
Thread
private
CubbyHole cubbyhole;
private int
number;
public
Producer(CubbyHole c,
int
number) {
cubbyhole = c;this.number = number; } public void
run() {
for
int
i = 0; i < 10; i++) {
cubbyhole.put(number, i); try
{ sleep((int)(Math.random() * 100)); }^
catch
(InterruptedException e) { }
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(number); } } }
CubbyHole
private int
contents;
private boolean
available = false;
public synchronized int
get(
int
who)
{ ... } public synchronized void
put(
int
who,
int
value)
get() {
while
(available == false) { try
{ //wait for Producer to put value wait(); }^
catch
(InterruptedException e) { }
} available = false;//notify Producer that value has been retrieved notifyAll(); return
contents;