2021年9月22日 星期三

My second Java Program - multithreading - SLOC=56

package waitNotify;

class Badminton { // 在羽球類別中,設定羽毛球物件的屬性和方法

   private boolean isShooting = false;

   public synchronized void sShuttlecock(int tNo) {

   while (isShooting) {

   try {

   wait();

   } catch (InterruptedException e) {}

   }

   System.out.println("射出第"+tNo+" 顆羽球");

   isShooting = true;

   notify();

   }

   public synchronized void hShuttlecock(int aNo) {

   while (!isShooting) {

   try {

   wait();

   } catch (InterruptedException e) {}

   }

   System.out.println("擊回第"+aNo+" 顆羽球");

   isShooting = false;

   notify();

   }

}

class Shooting implements Runnable{

Badminton shuttlecock;

Shooting (Badminton shuttlecock){

this.shuttlecock = shuttlecock;

}

public void run() {

for (int i = 1; i <= 5; i++) {

shuttlecock.sShuttlecock(i);

}

}

}

class Hit implements Runnable{

Badminton shuttlecock;

Hit (Badminton shuttlecock){

this.shuttlecock = shuttlecock;

}

public void run() {

for (int i = 1; i <= 5; i++) {

shuttlecock.hShuttlecock(i);

}

}

}

public class WaitNotify {

public static void main(String[] args) {

// TODO Auto-generated method stub

Badminton shuttlecock = new Badminton(); 

Thread machine = new Thread(new Shooting(shuttlecock));

Thread hitter = new Thread(new Hit(shuttlecock));

machine.start();

hitter.start();

}

}


2021年8月19日 星期四

My first Java program

package ex01;

import java.util.Scanner;

public class Hello {

      

      public static void main (String[] args) {

            Scanner scn  =  new Scanner(System.in);

            System.out.print("Please enter name:");

            String strName = scn.next(); /* declare a string variable named "strName", use scn.next() method to get what string a user entered, then assign to "strName". */

            System.out.println("Hi !" + strName + ",Welcome to Java world!");

            scn.close();

      }


}