By GokiSoft.com| 20:29 13/06/2020|
Java Advanced

[Share Code] Tìm hiểu về Thread - MultiThreading - Synchronized Trong Java - Lập trình java

[Share Code] Tìm hiểu về Thread - MultiThreading - Synchronized Trong Java - Lập trình java

#Cách khỏi tạo Thread và các hàm căn bản trong Thread

#CustomThread.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lession6;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author teacher
 */
public class CustomThread extends Thread{

    @Override
    public void run() {
        System.out.println("Start Thread 2");
        for (int i = 0; i < 100; i++) {
            System.out.println("T2 >> " + i);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        System.out.println("Stop Thread 2");
    }
    
}


#Main.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lession6;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author teacher
 */
public class Main {
    public static void main(String[] args) {
        //Thread tồn tại ở thời điểm này: Main Thread (Khi chưa sử dung join())
        //Hệ thống sẽ tạo ra 1 main thread (luồng chính)
        System.out.println("start main thread.");
        //Cách tạo 1 thread mới
        //Cách 1
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                //Khi thread t1 chay => goi vao ham nay dau tien.
                //viet code => cho thread 1 bat dau tu day.
                System.out.println("Start T1");
                for (int i = 0; i < 100; i++) {
                    System.out.println("T1 >> " + i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                System.out.println("Stop T1");
            }
        });
        //Thread tồn tại ở thời điểm này:  Main (Khi chưa sử dung join())
        //Cho Thread 1 chay
        t1.start();
        try {
            //Thread tồn tại ở thời điểm này: Main, T1 (Khi chưa sử dung join())
            t1.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        //Cách 2: Tạo thread
        //Thread tồn tại ở thời điểm này: Main,T1 (co the tồn tài nếu chưa kết thúc) (Khi chưa sử dung join())
        CustomThread t2 = new CustomThread();
        //Thread tồn tại ở thời điểm này: Main, T1 (co the tồn tài nếu chưa kết thúc) (Khi chưa sử dung join())
        t2.start();
        //Thread tồn tại ở thời điểm này: Main, T1 (co the tồn tài nếu chưa kết thúc), T2 (Khi chưa sử dung join())
        
        //Phân 2: Hiểu kỹ hơn về vòng đời của 1 Thread
        //1 Thread => Stop => TH1 : Khi xu ly het code trong Thread && t1.stop()
//        t1.stop();
//        t1.start();//Thread chi dc start() 1 lan duy nhat
       
        System.out.println("Stop Main Thread");
    }
}

#Xử lý đồng bộ Thread trong Java


#Test.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lession6;

/**
 *
 * @author teacher
 */
public class Test {
    public static void main(String[] args) {
        SharedData sharedData = new SharedData();
        sharedData.addMore(2);
        //x: 0, delta: 2
        //x: 2
        
        sharedData.addMore(3);
        //x: 2, delta: 3
        //x: 5
        
        sharedData.addMore(1);
        //x: 5, delta: 1
        //x: 6
        
        NewThread t1 = new NewThread(sharedData);
        NewThread t2 = new NewThread(sharedData);
        NewThread t3 = new NewThread(sharedData);
        NewThread t4 = new NewThread(sharedData);
        NewThread t5 = new NewThread(sharedData);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}


#NewThread.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lession6;

/**
 *
 * @author teacher
 */
public class NewThread extends Thread{
    SharedData sharedData;

    public NewThread(SharedData sharedData) {
        this.sharedData = sharedData;
    }
    
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            sharedData.addMore(1);
        }
    }
}


#SharedData.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lession6;

/**
 *
 * @author teacher
 */
public class SharedData {
    int x;
    int rad;

    public SharedData() {
        x = 0;
    }

    public int getRad() {
        return rad;
    }

    public void setRad(int rad) {
        this.rad = rad;
    }
    
    public synchronized void addMore(int delta) {
        System.out.println("x: " + x + "; delta: " + delta);
        x+=delta;
        System.out.println("x: " + x);
    }
}




Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)

Đăng nhập để làm bài kiểm tra

Chưa có kết quả nào trước đó