Advertisement
nikeza

Thread test

Apr 7th, 2020
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class MyTest {
  4.     public static void main(String[] args) {
  5.  
  6.         Scanner scanner = new Scanner(System.in);
  7.         Thread t1 = new Thread(() -> {
  8.             while (true) {
  9.                 System.out.println("Enter command...");
  10.                 String cmd = scanner.nextLine();
  11.                 if (Thread.interrupted()) {
  12.                     System.out.println(
  13.                             "Sorry, your command is disregarded, because your time has left!");
  14.                 }
  15.                 System.out.println("You have entered " + cmd);
  16.             }
  17.         });
  18.         Thread t2 = new Thread(() -> {
  19.             int x = 10;
  20.             while (x > 0) {
  21.                 try {
  22.                     Thread.sleep(1000);
  23.                 } catch (InterruptedException e) {
  24.                     e.printStackTrace();
  25.                 }
  26.                 x--;
  27.                 System.out.println("Seconds " + x);
  28.             }
  29.             t1.interrupt();
  30.             System.out.println("You cannot enter new commands!");
  31.         });
  32.         t1.start();
  33.         t2.start();
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement