F
F
fireb52016-04-28 23:25:54
Java
fireb5, 2016-04-28 23:25:54

How to stop threads with a key combination?

Good day. I am new to JAVA and I would like to know how to stop threads using CTRL+C key combination in console application. He himself tried to do something (he took an example from the book, but there was no stopping through combinations, he somehow tried to do it himself, but to no avail).
I will be very happy for help

package lab2;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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 put(int n) { 
        while(valueSet)
        try { 
            wait();
        } catch(InterruptedException e) { 
            System.out.println("InterruptedException перехвачено");
        }
        this.n = n; 
        valueSet = true;
        System.out.println("Отправлено: " + n); notify();
    }
            
}

class Producer implements Runnable {
    boolean pushButton;
    Q q; 

    Producer(Q q) { 
        this.q = q;
        new Thread(this, "Поставщик").start() ;
    }
    
    public void run() {    
        int i = 0;
        while(pushButton = true) {
            q.put(i++);
        }
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try 
        {
            int ascii = br.read();
            while (ascii != 10){
                pushButton = false;  
            }
  
        }
        catch (IOException e)
        {
            e.printStackTrace();
        } 
    }

}

class Consumer implements Runnable {
    boolean pushButton;
    Q q;
    Consumer(Q q) { 
        this.q = q;
        new Thread(this, "Потребитель").start();
    }
   
public void run() {
    
    while(pushButton = true) {
        q. get();
    }
            
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try 
        {
            int ascii = br.read();
            while (ascii != 10){
                pushButton = false;  
            }
  
        }
        catch (IOException e)
        {
            e.printStackTrace();
        } 
    }
}
 
class Lab2  { 
    public static void main(String[] args) 
    {

        Q q = new Q ();
        new Producer(q);
        new Consumer(q);

    } 

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
andryha8, 2016-10-07
@andryha8

On windows try Ctrl+D

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question