黑马程序员---线程

---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------

java.util.concurrent    //并发库

java.util.concurrent.atomic

java1.5创建线程方法

public class Demo {

	public static void main(String[] args) {

		// ExecutorService exe=Executors.newFixedThreadPool(3);
		 ExecutorService exe = Executors.newCachedThreadPool();
		// ExecutorService exe = Executors.newSingleThreadExecutor();
	/*	for (int i = 0; i < 10; i++) {
			final int task = i;
			exe.execute(new Runnable() {

				@Override
				public void run() {
					for (int j = 0; j < 10; j++) {
						try {
							Thread.sleep(50);
						} catch (InterruptedException e) {

							e.printStackTrace();
						}
						System.out.println("Thread name:"
								+ Thread.currentThread().getName() + "任务执行次数:"
								+ j + "任务号:" + task);
					}

				}

			});
		}
		exe.shutdown();// ExecutorService
*/		Executors.newScheduledThreadPool(3).schedule(new Runnable(){

			@Override
			public void run() {
				for (int i =1; i < 11; i++) {
				System.out.println("Thread name:"
						+ Thread.currentThread().getName());
				}
					
			}
			
		},1,TimeUnit.SECONDS);
	}
}


读写锁:

public class LockTest {
	ReentrantReadWriteLock lock= new ReentrantReadWriteLock();
	int i;
	public static void main(String[] args) {
		final LockTest l=new LockTest();
		for (int i = 0; i < 3; i++) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					while (true) {
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						l.read();
					}
				}

			}).start();

			new Thread(new Runnable() {

				@Override
				public void run() {
					while (true) {
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						l.write();
					}
				}

			}).start();
		}
		

	}
	void read(){
		lock.readLock().lock();
		try {
			System.out.println("开始读....."+Thread.currentThread().getName());
			Thread.sleep((long) (Math.random()*1000));
			System.out.println("这是读: "+Thread.currentThread().getName()+"值:"+i);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			
			lock.readLock().unlock();
		}
	}
	void write(){
		lock.writeLock().lock();
		try {
			++i;
			System.out.println("开始写....."+Thread.currentThread().getName());
			System.out.println("写: "+Thread.currentThread().getName()+"写值为:"+i);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			lock.writeLock().unlock();
			
		}
	}
}

可以多个线程同时读取读锁里的数据。但在读数据的线程没有释放锁的情况下,写的线程不能写,反之亦然,也就是说读写不能同时进行。在写锁的线程中,只能一个线程写入,禁止其他写线程进入写锁中。

 

Lock:

public class Demo2 {

	public static void main(String[] args) {
		final BB b=new BB();
		
		new Thread(new Runnable(){

			@Override
			public void run() {
				while(true){					
					b.one();
				}
			}
			
		}).start();
		new Thread(new Runnable(){
			
			@Override
			public void run() {
				while(true){					
					b.two();
				}
			}
			
		}).start();
		new Thread(new Runnable(){
			
			@Override
			public void run() {
				while(true){					
					b.three();
				}
			}
			
		}).start();
		
	}
}

class BB {
	Lock lock = new ReentrantLock();
	Condition one = lock.newCondition();
	Condition two = lock.newCondition();
	Condition three = lock.newCondition();
	int couts = 1;

	void one() {
		lock.lock();
		try {
			while (couts != 1) {
				try {
					one.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			couts++;
			System.out.println("one.......");
			two.signal();
		}finally{
			lock.unlock();
		}
	}

	void two() {
		lock.lock();
		try {
			while (couts != 2) {
				try {
					two.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			couts++;
			System.out.println("two.......");
			three.signal();
		}finally{
			lock.unlock();
		}

	}

	void three() {
		lock.lock();
		try {
			while (couts != 3) {
				try {
					three.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			couts=1;
			System.out.println("three.......");
			one.signal();
		}finally{
			lock.unlock();
		}


	}
}

Semaphore:

一个计数信号量。从概念上讲,信号量维护了一个许可集。如有必要,在许可可用前会阻塞每一个 acquire(),然后再获取该许可。每个 release() 添加一个许可,从而可能释放一个正在阻塞的获取者。但是,不使用实际的许可对象,Semaphore 只对可用许可的号码进行计数,并采取相应的行动。

Semaphore 通常用于限制可以访问某些资源(物理或逻辑的)的线程数目。

 

public class Test {
	public static void main(String[] args) {
	final	Semaphore semaphore=new Semaphore(1);//1为信号量数,允许线程访问的数量	
		
		for (int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					
					try {
						semaphore.acquire();//获得一个信号,没有获得信号的线程阻塞状态中
						System.out.println("Thread :"+Thread.currentThread().getName()+" 获得了信号");						
						System.out.println("哥出来了 要信号给你");
						semaphore.release();//释放一个信号。
						Thread.sleep(1000);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			}).start();
		}
		
	
		
	}
}


SynchronousQueue:

一种阻塞队列,其中每个put操作必须等待另一个线程的对应task操作 ,反之亦然。就是说put一个元素后,此线程要是还想put一个元素那必须得等task一个元素后才能put,同时线程进入阻塞状态。反过来也一样;

 

public class Test {

	public static void main(String[] args) {
		final SynchronousQueue<String> queue = new SynchronousQueue<String>();
		// 线程1
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {

					try {
						System.out.println("hi!哥们,我放个东西放你这啊,我等下来取,你别走啊");
						queue.put("AK-47");
						Thread.sleep(1000);//让线程sleep1秒是避免hi!哥们出现重复。因为put后可能线程还有cup执行权。
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
		// 线程2
			new Thread(new Runnable() {
				@Override
				public void run() {
					while(true){
					try {
						String str=queue.take();
						System.out.println("好,赶快过来取" + "物品:" +str);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				}
			}).start();
		
	}
}


 

public class Test {

	public static void main(String[] args) {
		final Semaphore semaphore=new Semaphore(1);
		final BlockingQueue<String> queue = new SynchronousQueue<String>();
		System.out.println("begin:" + (System.currentTimeMillis() / 1000));
		
		for (int i = 0; i < 10; i++) { 
			String input = i + ""; 

			try {
				System.out.println("fd");
				//put一个元素,线程就阻塞.等task()完了后线程才恢复,所以主线程阻塞,
				//下面的子线程启动不了,下面的for()应该放在此for()上。
				queue.put(input); 
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		for (int i = 1; i < 11; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {					
					try {
						semaphore.acquire();
						String str = (String) queue.take();
						String output = TestDo.doSome(str);
						System.out.println(Thread.currentThread().getName()
								+ ":" + output);
						semaphore.release();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();
		}		
	}
}

class TestDo {
	public static String doSome(String input) {

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		String output = input + ":" + (System.currentTimeMillis() / 1000);
		return output;
	}
}

 

LinkedBlockingDeque:(java1.6)

public class Test {
	public static void main(String[] args) {
		final LinkedBlockingDeque<Integer> queue = new LinkedBlockingDeque<Integer>(3);//队列的大小
		
		for (int i = 0; i < 3; i++) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					
					try {
						System.out.println("put couts:");
						queue.put(1);
						System.out.println("queue的大小:"+queue.size());						
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			}).start();
		}
		new Thread(new Runnable() {
				@Override
				public void run() {
					while(true){
					try {
						int temp=queue.take();
						System.out.println("take数据  "+"queue的大小:"+queue.size());
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				}
			}).start();
		
	}
}


 

---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------详细请查看:http://edu.csdn.net

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值