By GokiSoft.com| 15:22 27/03/2020|
Java Advanced

Share Code - Thread trong java + Thread.Sleep + join trong java BT1098

Source code bài giảng


Nội dung

- Thread : Luồng dữ liệu

- Synchronized : đồng bộ đa luồng

Lý do sử dụng Thread & tìm hiểu về thread


- Khi các bạn chơi game => Tiến trình

- Nhân vật game đang chạy -> thread (luồng)

- Cài đặt game -> 1 thread

- download file trên mạng -> 1 thread

- âm thanh vẫn đang play -> 1 thread


- Quan sát HĐH win/mac

- bật được rất nhiều app

=> chrome => 1 tiến trình

=> nghe nhạc => 1 tiến trình

=> code => 1 tiến trình

=> game => 1 tiến trình

=> chat ... =>tổng => 5 tiến trinh

- Round Robin => sắp xếp thành vòng tròn => hệ thống => sẽ thưc hiện là luôn phiên nhau xử lý lệnh cho chương trình

- 1s => CPU => hàng triệu lệnh

- tạo cho các bạn cảm giác như la tất cả các ứng dụng => đang chạy // => xử lý tuần tự


=> các bạn có suy nghĩ như thế nào về hoạt động của máy tính


Xây dựng 1 dự án đa luồng


Synchronized : đồng bộ đa luồng

- synchronized => methods

- wait, notify, notifyAll


/*
 * 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 java2.lession4;

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

/**
 *
 * @author Diep.Tran
 */
public class Main {
    public static void main(String[] args) {
        //Thread main => luong  chinh => khoi tao dau tien khi app dc bat
        //Cach 1
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                //goi toi xu ly code trong phan nay => khi ma t1.start() dc goi
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    System.out.println("t1 >> " + i);
                }
            }
        });
        t1.start();
        //Tai thoi diem nay => 2 thread >> t1 & main thread
        
        //Tao theo cach 2
        Thread t2 = new ThreadTwo("T2");
        t2.start();
        try {
            t2.join();
            //Tai thoi diem nay => 3 thread >> t1 & t2 & main thread
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        //Cach 3 >> tao ra thread
        ThreadThree r = new ThreadThree("T3");
        Thread t3 = new Thread(r);
        t3.start();
        
        //main thread
        for (int i = 0; i < 15; i++) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("T1 >> isAlive >> " + t1.isAlive());
            System.out.println("T2 >> isAlive >> " + t2.isAlive());
            System.out.println("T3 >> isAlive >> " + t3.isAlive());
            System.out.println("Main thread >> " + i);
        }
    }
}



/*
 * 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 java2.lession4;

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

/**
 *
 * @author Diep.Tran
 */
public class ThreadThree implements Runnable{
    String name;
    
    public ThreadThree(String name) {
        this.name = name;
    }

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



/*
 * 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 java2.lession4;

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

/**
 *
 * @author Diep.Tran
 */
public class ThreadTwo extends Thread{
    String name;
    
    public ThreadTwo(String name) {
        this.name = name;
    }

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



/*
 * 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 java2.lession4;

/**
 *
 * @author Diep.Tran
 */
public class MyBank {
    int money;

    public MyBank() {
    }

    public MyBank(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
    
    public synchronized void withDraw(int money, String threadName) {
        if(money <= this.money) {
            System.out.println("So tien rut : " + money + ", Thread : " + threadName);
            this.money -= money;
        } else {
            System.out.println("So tien rut vuot qua so tien hien tai" + ", Thread : " + threadName);
        }
        System.out.println("So tien hien tai: " + this.money);
    }
}



/*
 * 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 java2.lession4;

/**
 *
 * @author Diep.Tran
 */
public class WithDrawThread extends Thread{
    String name;
    MyBank myBank;
    public WithDrawThread(MyBank myBank, String name) {
        this.myBank = myBank;
        this.name = name;
    }

    @Override
    public void run() {
//        for (int i = 0; i < 10; i++) {
            myBank.withDraw(800, name);
//        }
    }
    
}


Liên kết rút gọn:

https://gokisoft.com/1098

Bình luận