By GokiSoft.com| 15:51 17/03/2021|
Java Advanced

[Share Code] Tìm hiểu về Thread - Synchronized Trong Java - Lập trình Java nâng cao

#ThreadTwo.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 aptech.java2.lesson04;

/**
 *
 * @author Diep.Tran
 */
public class ThreadTwo extends Thread{
    SharedData sharedData;

    public ThreadTwo(SharedData sharedData) {
        this.sharedData = sharedData;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
//            sharedData.minus(getName(), 1);
            synchronized(sharedData) {
                System.out.println(getName() + "->" + sharedData.count);
                sharedData.count -= 1;
                System.out.println(getName() + "->" + "Count:" + sharedData.count);
            }
        }
    }
    
    
}


#ThreadOne.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 aptech.java2.lesson04;

/**
 *
 * @author Diep.Tran
 */
public class ThreadOne extends Thread{
    SharedData sharedData;

    public ThreadOne(SharedData sharedData) {
        this.sharedData = sharedData;
    }
    
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
//            sharedData.add(getName(), 1);
            synchronized(sharedData) {
                System.out.println(getName() + "->" + sharedData.count);
                sharedData.count += 1;
                System.out.println(getName() + "->" + "Count:" + sharedData.count);
            }
        }
    }
    
}


#Thread2.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 aptech.java2.lesson04;

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

/**
 *
 * @author Diep.Tran
 */
public class Thread2 extends Thread{
    SharedData sharedData;

    public Thread2(SharedData sharedData) {
        this.sharedData = sharedData;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            synchronized(sharedData) {
                try {
                    sharedData.notifyAll();
                    sharedData.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                int rad = sharedData.getRad();
                rad *= rad;
                System.out.println("BT: " + rad);
            }
        }
        
        System.out.println("Finish Thread");
        synchronized(sharedData) {
            sharedData.notifyAll();
        }
        
    }
}


#Thread1.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 aptech.java2.lesson04;

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

/**
 *
 * @author Diep.Tran
 */
public class Thread1 extends Thread{
    SharedData sharedData;

    public Thread1(SharedData sharedData) {
        this.sharedData = sharedData;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        Random random = new Random();
        
        for (int i = 0; i < 10; i++) {
            synchronized(sharedData) {
                int rad = random.nextInt(10);
                sharedData.setRad(rad);
                System.out.println("Rad: " + rad);
                
                sharedData.notifyAll();
                
                try {
                    sharedData.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        System.out.println("Finish Thread");
        synchronized(sharedData) {
            sharedData.notifyAll();
        }
    }
    
    
}


#Test1.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 aptech.java2.lesson04;

/**
 *
 * @author Diep.Tran
 */
public class Test1 {
    public static void main(String[] args) {
        SharedData sharedData = new SharedData();
        
        Thread1 t1 = new Thread1(sharedData);
        Thread2 t2 = new Thread2(sharedData);
        
        t1.start();
        t2.start();
    }
}


#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 aptech.java2.lesson04;

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

/**
 *
 * @author Diep.Tran
 */
public class Test {
    public static void main(String[] args) {
        SharedData sharedData = new SharedData();
        
        Thread t1 = new ThreadTwo(sharedData);
        t1.setName("T1");
        Thread t2 = new ThreadOne(sharedData);
        t2.setName("T2");
        Thread t3 = new ThreadTwo(sharedData);
        t3.setName("T3");
        Thread t4 = new ThreadOne(sharedData);
        t4.setName("T4");
        Thread t5 = new ThreadTwo(sharedData);
        t5.setName("T5");
        
        t1.start();//Main + T1
//        try {
//            t1.join();
//        } catch (InterruptedException ex) {
//            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
//        }
        t2.start();//Main + T2 + T1
        t3.start();//Main + T3 + T2 + T1
//        System.out.println("Test ...");//Main + T3 + T2 + T1
        t4.start();//Main + T4 + T3 + T2 + T1
        t5.start();//Main + T5 + T4 + T3 + T2 + T1
    }
}


#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 aptech.java2.lesson04;

/**
 *
 * @author Diep.Tran
 */
public class SharedData {
    int count = 0;
    int rad;
    
    public synchronized void add(String threadName, int delta) {
        System.out.println(threadName + "->" + count);
        count += delta;
        System.out.println(threadName + "->" + "Count:" + count);
    }
    
    public synchronized void minus(String threadName, int delta) {
        System.out.println(threadName + "->" + count);
        count -= delta;
        System.out.println(threadName + "->" + "Count:" + count);
    }

    public int getRad() {
        return rad;
    }

    public void setRad(int rad) {
        this.rad = rad;
    }
}


#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 aptech.java2.lesson04;

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

/**
 *
 * @author Diep.Tran
 */
public class Main {
    public static void main(String[] args) {
        //Bat dau chuong trinh: Main Thread
        System.out.println("Main Thread -> Start");
        
        //Cach 1:
        //Khoi tao 1 thread len
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("T1 > " + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        t1.setName("ABC");
        CustomThread t2 = new CustomThread();
        t2.setName("BBB");
        
        //Thuc hien chay Thread
        t1.start();//Main Thread & T1
        try {
            t1.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        System.out.println("Xin chao");//
        
        t2.start();//Main Thread & T2
        
        try {
            t2.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        System.out.println("Hello ...");
        
        t2.stop();//T2 -> stop -> goi tiep ham stop() -> ko tac dung.
        //Note: Khi thread -> stop -> khoi tao doi tuong Thread len -> start().
        t2 = new CustomThread();
        t2.setName("KKK");
        t2.start();
        
        System.out.println("Main Thread -> Stop");
    }
}


#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 aptech.java2.lesson04;

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

/**
 *
 * @author Diep.Tran
 */
public class CustomThread extends Thread {

    @Override
    public void run() {
        System.out.println(getName() + " -> CustomThread > Start");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        for (int i = 0; i < 10; i++) {
            System.out.println(getName() + " -> CustomThread > " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        System.out.println(getName() + " -> CustomThread > Stop");
    }

}


Tags:

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

5

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