Thứ Năm, 29 tháng 6, 2017

[Thực tập] Buổi 3: Ôn tập kiến thức nền tảng Java

1. Generic
Khi muốn viết một phương thức dùng chung cho tất cả các kiểu String, Integer, Char... thì Generic là một kỹ thuật giúp thực hiện điều đó. Một ví dụ:
public class GenericMethodTest
{
   // phuong thuc generic co ten la printArray                         
   public static < E > void printArray( E[] inputArray )
   {
      // Hien thi cac phan tu mang              
         for ( E element : inputArray ){        
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }

    public static void main( String args[] )
    {
        // Tao cac mang Integer, Double va Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

        System.out.println( "Mang intArray bao gom:" );
        printArray( intArray  ); 

        System.out.println( "\nMang doubleArray bao gom:" );
        printArray( doubleArray ); 

        System.out.println( "\nMang charArray bao gom:" );
        printArray( charArray ); 
    } 
}
Kết quả:
1 2 3 4 5
1.1 2.2 3.3 4.4
H E L L O
2. Serialization
 Serialization là kỹ thuật ghi các trạng thái dữ liệu của một đối tượng vào một luồng byte. Khi đó dữ liệu của đối tượng sẽ được ghi lại một cách có thứ tự sắp xếp và đọc ra một cách dễ dàng.
 Cú pháp là lớp đối tượng phải implement Serilalization

Ví dụ:
Có 3 lớp Employee, SerializationDemo, DeserializeDemo:

Lớp Employee:
public class Employee implements java.io.Serializable{
       public String name;
       public String address;
       public transient int SSN;
       public int number;
       public void mailCheck(){
           System.out.println("Gui mail toi "+name+" tai dia chi "+address);
       }

    public Employee(String name, String address,int SSN, int number) {
        this.name = name;
        this.address = address;
        this.SSN = SSN;
        this.number = number;
    }
   
      
}
 

 Lớp  SerializationDemo
 class SerializationDemo {
    public static void main(String args[]) throws IOException{
 
            FileOutputStream fileOut = null;
            Employee e = new Employee("Tuan", "Ha noi", 123, 123);
            Employee e1 = new Employee("Ngoan", "Ha noi", 120, 123);
            Employee e2 = new Employee("Chung", "Thai Binh", 100, 100);
            fileOut = new FileOutputStream("employee.ser");
            ObjectOutputStream out= new ObjectOutputStream(fileOut);
            out.writeObject(e);
            out.writeObject(e1);
            out.writeObject(e2);
            fileOut.close();
            System.out.println("Du lieu da Serialize duoc luu tru trong employee.ser");
         
    }

}

 Lớp DeSerialization
public class DeserializeDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException{
        Employee e = null;
        Employee e1 = null;
        Employee e2 = null;
        FileInputStream fileIn = new FileInputStream("employee.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);
        e = (Employee) in.readObject();
        e1 = (Employee) in.readObject();
       
        e2 = (Employee) in.readObject();
      
        fileIn.close();
        System.out.println(e.name+" "+e.address+" "+e.SSN+" "+e.number);
        System.out.println(e1.name+" "+e1.address+" "+e1.SSN+" "+e1.number);
        System.out.println(e2.name+" "+e2.address+" "+e2.SSN+" "+e2.number);
    }
}

3.Thread
Là kỹ thuật cho phép thực hiện nhiều tác vụ đồng thời trong Java. Một chương trình Java có thể chia làm nhiều phần và cùng chạy đồng thời, mỗi phần xử lý một tác vụ khác nhau, Mục đích để tận dụng tài nguyên, nhất là khi máy tính có nhiều CPU.

Có hai cách để cài đặt một lớp là Thread:
- implements Runnable
 - extends Thead


Ví dụ 1: Cài đặt thread bằng cách implements Runnable:
class RunnableDemo implements Runnable {
   private Thread t;
   private String threadName;
   
   RunnableDemo( String name){
       threadName = name;
       System.out.println("Creating " +  threadName );
   }
   public void run() {
      System.out.println("Running " +  threadName );
      try {
         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // De thread ngung trong choc lat.
            Thread.sleep(50);
         }
     } catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
     }
     System.out.println("Thread " +  threadName + " exiting.");
   }
   
   public void start ()
   {
      System.out.println("Starting " +  threadName );
      if (t == null)
      {
         t = new Thread (this, threadName);
         t.start ();
      }
   }

}

public class TestThread {
   public static void main(String args[]) {
   
      RunnableDemo R1 = new RunnableDemo( "Thread-1");
      R1.start();
      
      RunnableDemo R2 = new RunnableDemo( "Thread-2");
      R2.start();
   }   
}
 
Ví dụ 2: Cài đặt thread bằng extends class Thread


class ThreadDemo extends Thread {
   private Thread t;
   private String threadName;
   
   ThreadDemo( String name){
       threadName = name;
       System.out.println("Creating " +  threadName );
   }
   public void run() {
      System.out.println("Running " +  threadName );
      try {
         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // Let the thread sleep for a while.
            Thread.sleep(50);
         }
     } catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
     }
     System.out.println("Thread " +  threadName + " exiting.");
   }
   
   public void start ()
   {
      System.out.println("Starting " +  threadName );
      if (t == null)
      {
         t = new Thread (this, threadName);
         t.start ();
      }
   }

}

public class TestThread {
   public static void main(String args[]) {
   
      ThreadDemo T1 = new ThreadDemo( "Thread-1");
      T1.start();
      
      ThreadDemo T2 = new ThreadDemo( "Thread-2");
      T2.start();
   }   
}

DaemonThread
  • Daemon Thread  dùng để cung cấp các dịch vụ cho các luồng người dùng. Nó sẽ bị JVM hủy khi không có Thread nào của user.
  • Daemon Thread có độ ưu tiên thấp 
  • Chú ý khi một thread start() rồi thì không được phép setDaemon() cho thread này nữa.
Ví dụ: 
Để hiểu rõ hơn về DaemonThread thì cùng xem ví dụ sau, mặc dù hàm run chạy vòng lặp vô hạn tuy nhiên khi vào chương trình thì kết trả in ra các dòng hello và bye chỉ nằm trong hữu hạn. Vì do các thread là daemon tự động bị JVM. 
 

Không có nhận xét nào:

Đăng nhận xét