Answer the question
In order to leave comments, you need to log in
It is not clear what is wrong with the program?
Hello! I'm learning Java from the latest edition of Schildt's book, and I'm having an error with one of the examples. This code displays only "To stop, press Ctrl-C" in the console, and the work of the threads itself is not displayed. What could be the problem?
public class Q {
int n;
boolean valueSet = false;
synchronized int get(){
while(!valueSet)
try{
wait();
} catch(InterruptedException e){
System.out.println("Исключение типа InterruptedException перехвачено");
}
System.out.println("Получено: " + n);
valueSet = false;
notify();
return n;
}
synchronized void out(int n){
while(valueSet)
try{
wait();
} catch(InterruptedException e){
System.out.println("Исключение типа InterruptedException перехвачено");
}
this.n = n;
valueSet = true;
System.out.println("отправлено: " + n);
notify();
}
public void put(int i) {
i++;
}
}
class Producer implements Runnable{
Q q;
Producer(Q q){
this.q = q;
new Thread(this, "Поставщик").start();
}
@Override
public void run() {
int i = 0;
while(true){
q.put(i++);
}
}
}
class Consumer implements Runnable{
Q q;
Consumer(Q q){
this.q = q;
new Thread(this, "Потребитель").start();
}
@Override
public void run() {
while (true) {
q.get();
}
}
}
class PCFixed {
public static void main(String args[]){
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Для остановки нажмите Ctrl-C");
}
}
Answer the question
In order to leave comments, you need to log in
you learn from the 8th edition
, then there is such a code
// the correct implementation of the supplier and consumer.
class Q {
int n;
boolean valueSet = false;
synchronized int get () {
while ( ! valueSet )
try {
wait ();
} catch ( InterruptedException e ) {
System. out. println ( " InterruptedException perehvacheno ");
}
System.out.println ( " Polycheno " + n );
valueSet = false;
notify();
return n;
}
synchronized void put ( int n) {
while ( valueSet)
try {
wait ();
} catch ( InterruptedException e ) {
System.out.println("InterruptedException perehvacheno");
}
this.n = n;
valueSet = true;
System.out.println("Sentpravleno:" + n);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer ( Qq) {
this.q = q;
new Thread( this, " Postavshik " ).start();
}
public void run () {
int i =0;
while (true) {
q. put ( i++ );
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Qq) {
this.q = q;
new Thread( this, " Potrebitel " ).start();
}
public void run() {
while ( true ) {
q.get();
}
}
}
class PC {
public static void main ( String args []) {
Q q = new Q ();
new Producer(q);
new Consumer(q);
System.out.println("Dli ostanvci nagmite Control-C.");
}
}
besides messages, these are my inscriptions
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question