Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. public class Solution {
  2. public static volatile Runway RUNWAY = new Runway(); //1 взлетная полоса
  3.  
  4. public static void main(String[] args) throws InterruptedException {
  5. Plane plane1 = new Plane("Самолет #1");
  6. Plane plane2 = new Plane("Самолет #2");
  7. Plane plane3 = new Plane("Самолет #3");
  8. }
  9.  
  10. private static void waiting() {
  11. //add your code here - добавь код тут
  12. try{
  13. Thread.sleep(100);
  14. }catch(InterruptedException e){
  15.  
  16. }
  17. }
  18.  
  19. private static void takingOff() {
  20. //fix this method - исправь этот метод
  21. try {
  22. Thread.sleep(100);
  23. } catch (InterruptedException e) {
  24. }
  25. }
  26.  
  27. public static class Plane extends Thread {
  28. public Plane(String name) {
  29. super(name);
  30. start();
  31. }
  32.  
  33. public void run() {
  34. boolean isAlreadyTakenOff = false;
  35. while (!isAlreadyTakenOff) {
  36. if (RUNWAY.trySetTakingOffPlane(this)) { //если взлетная полоса свободна, занимаем ее
  37. System.out.println(getName() + " взлетает");
  38. takingOff();//взлетает
  39. System.out.println(getName() + " уже в небе");
  40. isAlreadyTakenOff = true;
  41. RUNWAY.setTakingOffPlane(null);
  42. } else if (!this.equals(RUNWAY.getTakingOffPlane())) { //если взлетная полоса занята самолетом
  43. System.out.println(getName() + " ожидает");
  44. waiting(); //ожидает
  45. }
  46. }
  47. }
  48. }
  49.  
  50. public static class Runway { //взлетная полоса
  51. private Thread t;
  52.  
  53. public Thread getTakingOffPlane() {
  54. return t;
  55. }
  56.  
  57. public void setTakingOffPlane(Thread t) {
  58. synchronized (this) {
  59. this.t = t;
  60. }
  61. }
  62.  
  63. public boolean trySetTakingOffPlane(Thread t) {
  64. synchronized (this) {
  65. if (this.t == null) {
  66. this.t = t;
  67. return true;
  68. }
  69. return false;
  70. }
  71. }
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement