码迷,mamicode.com
首页 > 编程语言 > 详细

多线程与并发03

时间:2016-07-17 09:39:04      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

/* 线程同步 
 * 1、同步代码块  2、同步方法  3、Lock
 * */

import java.util.concurrent.locks.ReentrantLock;
public class Thread03 {
    public static void main(String[] args) {
        Runnable r1 = new MyRunnable();
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r1);
        t1.start();
        t2.start();
    }
}

class MyRunnable implements Runnable {
    private int flag;
    @Override
    public void run() {
        this.compose();// 不能达到预期的0->1...
        // 同步代码块
        // this.synchronizedCodeBlockMethod();
        // 同步方法
        // this.synchronizedMethod();
        // 互斥锁
        // this.reentrantLockMethod();
    }

    // 同步代码块
    private Object obj = new Object();
    public void synchronizedCodeBlockMethod() {
        synchronized (obj) {
            this.compose();
        }
    }

    // 同步方法
    public synchronized void synchronizedMethod() {
        this.compose();
    }

    // 互斥锁
    private final ReentrantLock lock = new ReentrantLock();
    public void reentrantLockMethod() {
        this.lock.lock();
        this.compose();
        this.lock.unlock();
    }

    public void compose() {
        for (int i = 0; i < 5; i++) {
            this.flag = 0;
            System.out.println("程序开始-" + this.flag);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.flag = 1;
            System.out.println("程序结束-" + this.flag);
        }
    }
}

 

多线程与并发03

标签:

原文地址:http://www.cnblogs.com/xiaowangzhi/p/5677212.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!