java 线程

package com.lz.review;

/*
 * 代理模式实现线程
 * 优点:1.避免了通过继承Thread类时只能单继承的尴尬
 *         2.更方便共享数据
 */
public class Review01 {
    public static void main(String[] args) throws InterruptedException {
        MyRunnable mr = new MyRunnable();
        /*
         * 代理线程
         */
        Thread thread1 = new Thread(mr, "黄牛");
        Thread thread2 = new Thread(mr, "老黄牛");
        thread1.start();
        thread2.start();
        // int i = 0;
        // while (i++ < 100) {
        // /*
        // * 阻塞main线程
        // */
        // thread1.join();
        // System.out.println(Thread.currentThread().getName()+">>>"+i);
        // if (i > 10) {
        // /*
        // * 暂停thread2线程
        // */
        // Thread.yield();
        // }
        // }
    }

}

/*
 * 线程实体
 */
class MyRunnable implements Runnable {
    int cnt = 50;
    boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            myRun();
        }
    }
    
    /*
     * synchronized修饰符保证线程安全
     */
    private synchronized void myRun() {
        System.out.println(Thread.currentThread().getName() + ">>>" + cnt--);
        if (cnt <= 1)
            flag = false;
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        this.flag = false;
    }
}

 

你可能感兴趣的:(java 线程)