Write a producer, consumer multi-threaded program, a thread randomly generate data, and another thread displays the resulting da

xiaoxiao2021-03-06  99

Import java.util. *;

public class ThreadSample {private boolean stop_produce = false; private boolean stop_consume = false; private Vector data; private Thread producer; private Thread consumer; private Random random; public ThreadSample ()

{Data = new vector (); random = new random (); product = new thread () {public void run () {Try {while (! Stop_produce) {

Sleep (1000); productData ();

}

Catch (Exception E) {}

}};

While (! stop_consume) {Sleep (1000); consumedata ();}}

Catch (Exception E) {}}};

}

Public void startproduce () {// if (product.isinterrupted ()) stop_produce = false; product ();

Public void stopproduce () {stop_produce = true;

Public void stopconsume () {stop_consume = true;

Public void startconsume () {// if (consumer.isinterrupted ()) stop_consume = false; consumer.start ();}

Private synchronized void products () {integer i = new integer (random.nextint (100));

Data.Add (i);

}

Private synchronized void consumedata () {if (data.size ()! = 0) {//system.out.println (DATA); system.out.println (data.nextint (Data.Size ()) );

public static void main (String [] args) {ThreadSample threadsample = new ThreadSample (); threadsample.startProduce (); threadsample.startConsume (); try {Thread.sleep (50000); threadsample.stopProduce (); threadsample.stopConsume ( } Catch (Exception E) {}

}

}

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

New Post(0)