当前位置:首页 > 开发 > 编程语言 > 多线程 > 正文

java5中的线程同步

发表于: 2014-07-07   作者:a67474506   来源:转载   浏览:
摘要: package cn.zto.countdownlatch; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; //使用countdownLathch类实现线程同步 publi
package cn.zto.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//使用countdownLathch类实现线程同步
public class CountdownLatchTest {

	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		final CountDownLatch cdOrder = new CountDownLatch(1);
		final CountDownLatch cdAnswer = new CountDownLatch(3);

		for (int i = 1; i <= 3; i++) {
			Runnable runnable = new Runnable() {
				@Override
				public void run() {
					try {
						System.out.println("线程"
								+ Thread.currentThread().getName() + "正准备接受命令");
						cdOrder.await();
						System.out.println("线程"
								+ Thread.currentThread().getName() + "已接受命令");
						Thread.sleep((long) (Math.random() * 10000));
						System.out
								.println("线程"
										+ Thread.currentThread().getName()
										+ "回应命令处理结果");
						cdAnswer.countDown();
					} catch (Exception e) {

					}
				}
			};
			service.execute(runnable);
		}
		try {
			Thread.sleep((long) (Math.random() * 10000));

			System.out.println("线程" + Thread.currentThread().getName()
					+ "即将发布命令");
			cdOrder.countDown();
			System.out.println("线程" + Thread.currentThread().getName()
					+ "已发送命令,正在等待结果");
			cdAnswer.await();
			System.out.println("线程" + Thread.currentThread().getName()
					+ "已收到所有响应结果");
		} catch (Exception e) {
			e.printStackTrace();
		}
		service.shutdown();

	}
}

 

运行结果:

 

线程pool-1-thread-2正准备接受命令
线程pool-1-thread-3正准备接受命令
线程pool-1-thread-1正准备接受命令
线程main即将发布命令
线程main已发送命令,正在等待结果
线程pool-1-thread-2已接受命令
线程pool-1-thread-3已接受命令
线程pool-1-thread-1已接受命令
线程pool-1-thread-3回应命令处理结果
线程pool-1-thread-2回应命令处理结果
线程pool-1-thread-1回应命令处理结果
线程main已收到所有响应结果

 

package cn.zto.cyclicbarrier;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//使用CyclicBarrier实现线程同步
public class CyclicBarrierTest {
	
	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		
		final CyclicBarrier cb = new CyclicBarrier(3);
		for (int i = 1; i <= 3; i++) {
			Runnable runnable = new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep((long) (Math.random()*10000));
					
						System.out.println("线程" + Thread.currentThread().getName() + 
								"即将到达集合地点1,当前已有" + (cb.getNumberWaiting()+1) +
								"个已经到达," + (cb.getNumberWaiting()==2?"都到齐了,继续走啊":"正在等候"));
						cb.await();
						
						Thread.sleep((long) (Math.random()*10000));
						System.out.println("线程" + Thread.currentThread().getName() + 
								"即将到达集合地点2,当前已有" + (cb.getNumberWaiting()+1) +
								"个已经到达," + (cb.getNumberWaiting()==2?"都到齐了,继续走啊":"正在等候"));
						cb.await();
						
						Thread.sleep((long) (Math.random()*10000));
						System.out.println("线程" + Thread.currentThread().getName() + 
								"即将到达集合地点3,当前已有" + (cb.getNumberWaiting()+1) +
								"个已经到达," + (cb.getNumberWaiting()==2?"都到齐了,回家吧":"正在等候"));
						cb.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			
			service.execute(runnable);
		}
		
		service.shutdown();
	}
}

 

运行结果:

 

线程pool-1-thread-2即将到达集合地点1,当前已有1个已经到达,正在等候
线程pool-1-thread-1即将到达集合地点1,当前已有2个已经到达,正在等候
线程pool-1-thread-3即将到达集合地点1,当前已有3个已经到达,都到齐了,继续走啊
线程pool-1-thread-3即将到达集合地点2,当前已有1个已经到达,正在等候
线程pool-1-thread-1即将到达集合地点2,当前已有2个已经到达,正在等候
线程pool-1-thread-2即将到达集合地点2,当前已有3个已经到达,都到齐了,继续走啊
线程pool-1-thread-3即将到达集合地点3,当前已有1个已经到达,正在等候
线程pool-1-thread-2即将到达集合地点3,当前已有2个已经到达,正在等候
线程pool-1-thread-1即将到达集合地点3,当前已有3个已经到达,都到齐了,回家吧

 

package cn.zto.exchanger;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//通过exchanger实现线程同步
public class ExchangerTest {
	
	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		final Exchanger exchanger = new Exchanger();
		
		service.execute(new Runnable(){
			public void run() {
				try {				

					String data1 = "XXXXX";
					System.out.println("线程" + Thread.currentThread().getName() + 
					"正在把数据" + data1 +"换出去");
					Thread.sleep((long)(Math.random()*10000));
					String data2 = (String)exchanger.exchange(data1);
					System.out.println("线程" + Thread.currentThread().getName() + 
					"换回的数据为" + data2);
				}catch(Exception e){
					
				}
			}	
		});
		service.execute(new Runnable(){
			public void run() {
				try {				

					String data1 = "YYYYY";
					System.out.println("线程" + Thread.currentThread().getName() + 
					"正在把数据" + data1 +"换出去");
					Thread.sleep((long)(Math.random()*10000));					
					String data2 = (String)exchanger.exchange(data1);
					System.out.println("线程" + Thread.currentThread().getName() + 
					"换回的数据为" + data2);
				}catch(Exception e){
					
				}				
			}	
		});	
	}
}

 

运行结果:

线程pool-1-thread-1正在把数据XXXXX换出去
线程pool-1-thread-2正在把数据YYYYY换出去
线程pool-1-thread-2换回的数据为XXXXX
线程pool-1-thread-1换回的数据为YYYYY

 

package cn.zto.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

//信号灯
public class SemaphoreTest {
	
	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		
		final Semaphore sp = new Semaphore(3);
		
		for (int i = 1; i < 10; i++) {
			Runnable runnable = new Runnable() {
				
				@Override
				public void run() {
					try {
						sp.acquire();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("线程" + Thread.currentThread().getName() + 
							"进入,当前已有" + (3-sp.availablePermits()) + "个并发");
					try {
						Thread.sleep((long)(Math.random()*10000));
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("线程" + Thread.currentThread().getName() + 
							"即将离开");					
					sp.release();
					//下面代码有时候执行不准确,因为其没有和上面的代码合成原子单元
					System.out.println("线程" + Thread.currentThread().getName() + 
							"已离开,当前已有" + (3-sp.availablePermits()) + "个并发");		
				}
			};

			service.execute(runnable);
			
		}
	}
}

 

运行结果:

线程pool-1-thread-1进入,当前已有2个并发
线程pool-1-thread-2进入,当前已有2个并发
线程pool-1-thread-4进入,当前已有3个并发
线程pool-1-thread-2即将离开
线程pool-1-thread-5进入,当前已有3个并发
线程pool-1-thread-2已离开,当前已有3个并发
线程pool-1-thread-1即将离开
线程pool-1-thread-1已离开,当前已有2个并发
线程pool-1-thread-6进入,当前已有3个并发
线程pool-1-thread-4即将离开
线程pool-1-thread-4已离开,当前已有2个并发
线程pool-1-thread-9进入,当前已有3个并发
线程pool-1-thread-5即将离开
线程pool-1-thread-8进入,当前已有3个并发
线程pool-1-thread-5已离开,当前已有3个并发
线程pool-1-thread-6即将离开
线程pool-1-thread-6已离开,当前已有2个并发
线程pool-1-thread-3进入,当前已有3个并发
线程pool-1-thread-9即将离开
线程pool-1-thread-7进入,当前已有3个并发
线程pool-1-thread-9已离开,当前已有3个并发
线程pool-1-thread-3即将离开
线程pool-1-thread-3已离开,当前已有2个并发
线程pool-1-thread-8即将离开
线程pool-1-thread-8已离开,当前已有1个并发
线程pool-1-thread-7即将离开
线程pool-1-thread-7已离开,当前已有0个并发

 

 

 

java5中的线程同步

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
从这一篇开始我们将看看Java 5之后给我们添加的新的对线程操作的API,首先看看api文档: java.util.c
本文主要用来说明多线程中异常情况的处理。 问题出现:使用Lock进行多线程中的同步的时候,如果在Lo
C#中的线程(二)线程同步 C#中的线程(二)线程同步 Keywords:C# 线程 Source:http://www.albaha
我们先来看一下ExecutorService中的执行方法: 在上一篇中我们使用了execute方法启动线程池中的线程
允许一系列的集合等待彼此,到达一个共同的障碍物点. 表示大家彼此等待,大家集合好后才开始出发,分散
详细代码如下: public class CountdownLatchTest { public static void main(String[] args) { Exec
在JDK1.5之前没有推出同步集合的时候,可以通过Conllections集合工具类的synchronized+集合名称如:sy
Java SE7 API - Thread: http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#yield%2
今天效率需要,需要搞定一个多线程的程序,今天我用的关键字是Monitor.Enter(this);和Monitor.Exit(
代码 using System; using System.Collections.Generic; using System.Linq; using System.Text; us
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号