<转:>
程序举例:
代码:
- package com.synch;
- public class SynchronizedDemo {
- //共享变量
- private boolean ready = false;
- private int result = 0;
- private int number = 1;
- //写操作
- public synchronized void write(){
- ready = true;
- number = 2;
- }
- //读操作
- public synchronized void read(){
- if(ready){
- result = number*3;
- }
- System.out.println("result的值为:" + result);
- }
- //内部线程类
- private class ReadWriteThread extends Thread {
- //根据构造方法中传入的flag参数,确定线程执行读操作还是写操作
- private boolean flag;
- public ReadWriteThread(boolean flag){
- this.flag = flag;
- }
- @Override
- public void run() {
- if(flag){
- //构造方法中传入true,执行写操作
- write();
- }else{
- //构造方法中传入false,执行读操作
- read();
- }
- }
- }
- public static void main(String[] args) {
- SynchronizedDemo synDemo = new SynchronizedDemo();
- //启动线程执行写操作
- synDemo .new ReadWriteThread(true).start();
- // try {
- // Thread.sleep(1000);
- // } catch (InterruptedException e) {
- // // TODO Auto-generated catch block
- // e.printStackTrace();
- // }
- //启动线程执行读操作
- synDemo.new ReadWriteThread(false).start();
- }
- }
代码示例:
- package com.synch;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class VolatileDemo {
- private Lock lock = new ReentrantLock();
- private int number = 0;
- public int getNumber(){
- return this.number;
- }
- public void increase(){
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- lock.lock();
- try {
- this.number++;
- } finally {
- lock.unlock();
- }
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- final VolatileDemo volDemo = new VolatileDemo();
- for(int i = 0 ; i < 500 ; i++){
- new Thread(new Runnable() {
- @Override
- public void run() {
- volDemo.increase();
- }
- }).start();
- }
- //如果还有子线程在运行,主线程就让出CPU资源,
- //直到所有的子线程都运行完了,主线程再继续往下执行
- while(Thread.activeCount() > 1){ //让所有的子线程都执行完后,然后再执行<pre name="code" class="java">//System.out.println("number : " + volDemo.getNumber()); 语句。因为主线程算一个。当活跃线程为1时,也就是所有的子线程执行完毕了。此///时退出while 循环执行输出语句。