Saturday, October 5, 2013

Đa luồng trong java sử dụng Thread

Tạo 2 luồng, luồng T1 sinh ra 1 số nguyên ngẫu nhiên sau 1s, luồng T2 lấy số đó nhân với 20, không sử dụng sync


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package threadx2;
import java.util.Random;
/**
 *
 * @author Cuong
 */
public class EThread {
    private static int num;
    private static Random rd;
    public static void delay(int miliseconds) {
        try {
            Thread.sleep(miliseconds);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    // thread1 lay 1 so ngau nhien sau 1s
    static class Thread1 extends Thread {
        public void run() {
            rd = new Random();
            while (true) {
                num = rd.nextInt(100);
                System.out.println("T1: " + num);
                delay(1000);
            }
        }
    }
    // thread2 lay so num*20
    static class Thread2 extends Thread {
        public void run() {
            while (true) {
                System.out.println("T2: " + num + "*20=" + (num * 20));
                delay(1000);
            }
        }
    }
    public static void main(String[] args) {
        Thread1 th1 = new Thread1();
        Thread2 th2 = new Thread2();
        th1.start();
        th2.start();
    }
}

No comments:

Post a Comment