Thread的基本操作02

Lock和Condition

<span style="font-size:24px;">package 线程Demo;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

</span><span style="color:#33cc00;font-size:24px;">/**
 * JDK1.5提供了多线程升级解决方案 将同步中synchronized替换为lock 将Object提供的wait notify
 * notifyAll方法替换为Condition 该对象可以通过Lock获取
 */</span><span style="font-size:24px;">
<span style="color:#33cc00;">/*商品消费模式:多个线程参与,两个线程负责生产,两个线程负责消费*/</span>
class Goods {
	private String name;
	private int price;
	int number = 1;
	boolean flog = false;

	Lock lo = new ReentrantLock();<span style="color:#33cc00;">//创建Lock对象</span>
	Condition c1 = lo.newCondition();<span style="color:#33cc00;">//利用Lock对象获取</span></span><span style="font-size: 24px;"><span style="color:#33cc00;">Condition</span></span><span style="font-size:24px;">
	Condition c2 = lo.newCondition();

	public Goods(String name, int price) {
		super();
		this.name = name;
		this.price = price;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

	public void goodsProduction() {
		lo.lock();<span style="color:#33cc00;">//获取锁</span>
		try {
			while (flog) {
				try {
					c1.await();<span style="color:#33cc00;">//await()方法代替了wait()方法</span>
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println(Thread.currentThread().getName() + "生产了商品"
					+ name + "编号:" + (++number) + "价格为" + price);
			flog = true;
			c2.signal();//signal()方法代替了notify()方法
		} finally {<span style="color:#33cc00;">//这个动作必须执行</span>
			lo.unlock();<span style="color:#33cc00;">//释放锁</span>
		}

	}

	public void goodsConsumption() {
		lo.lock();
		try {
			while (!flog) {
				try {
					c2.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out
					.println(Thread.currentThread().getName()
							+ "----------消防了商品" + name + "编号:" + number + "价格为"
							+ price);
			flog = false;
			c1.signal();
		} finally {

			lo.unlock();
		}

	}
}

class sc implements Runnable {
	Goods go;

	public sc(Goods go) {
		this.go = go;
	}

	@Override
	public void run() {
		while (true) {
			go.goodsProduction();
		}

	}

}

class xf implements Runnable {
	Goods go;

	public xf(Goods go) {
		this.go = go;
	}

	@Override
	public void run() {
		while (true) {
			go.goodsConsumption();
		}

	}
}

public class LockDemo {

	public static void main(String[] args) {
		Goods go = new Goods("哇哈哈", 3);
		sc s = new sc(go);
		xf x = new xf(go);

		Thread t1 = new Thread(s);
		Thread t2 = new Thread(s);
		Thread t3 = new Thread(x);
		Thread t4 = new Thread(x);
		t1.start();
		t2.start();
		t3.start();
		t4.start();

	}

}
</span>
传统的定时器Timer演示

package 线程Demo02;

import java.util.Timer;
import java.util.TimerTask;

<span style="color:#33cc00;">/**
 * 传统的定时器演示
 */</span>
public class Traditional_Timer_Test01 {
	
	public static void main(String[] args) {
		Timer timer = new Timer();<span style="color:#33cc00;">// 创建定时器对象</span>
		
		<span style="color:#33cc00;">//执行一次的定时器</span>
		timer.schedule( <span style="color:#33cc00;">// 安排执行的代码</span>
				new TimerTask() {<span style="color:#33cc00;">//将要执行的代码封装到这个new TimerTask(){}对象中的run()方法中去</span>

					@Override
					public void run() {
						System.out.println("第一个定时器开始了");

					}
				}, 5000);
		
		<span style="color:#33cc00;">//连续执行的定时器</span>
		
		timer.schedule( <span style="color:#33cc00;">// 安排执行的代码</span>
				new TimerTask() {<span style="color:#33cc00;">//将要执行的代码封装到这个对象中的run()方法中去</span>
					private int a=1;
					@Override
					public void run() {
						System.out.println("第二个定时器开始了我被执行了"+(a++));

					}
				}, 3000,3000);

	}

}


package 线程Demo02;

import java.util.Timer;
import java.util.TimerTask;
<span style="color:#33cc00;">/**
 * 传统的定时器演示:
 * 		炸弹时间来回间的切换(2秒以后炸,然后4秒炸,然后2秒炸)
 */</span>
public class Traditional_Timer_Test02 {


	static int count=0;
	public static void main(String[] args) {
		
		
		class MyTimerTask extends TimerTask {
			
			@Override
			public void run() {
				count=(count+1)%2;
				System.out.println("A炸弹开始爆炸"+count);
				new Timer().schedule(new MyTimerTask(), 2000+2000*count);<span style="color:#33cc00;">//在创建一个新炸弹</span>
			}

		}
		new Timer().schedule(new MyTimerTask(), 2000);
		
	
	}

}
JDK1.5提供的线程池

package 线程Demo02;

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

<span style="color:#33cc00;">/**
 * JDK1.5提供的线程池
 */</span>
public class ThreadPool {

	public static void main(String[] args) {
		<span style="color:#33cc00;">// 创建固定大小的线程池</span>
		ExecutorService eService01 = Executors.newFixedThreadPool(5);

		<span style="color:#33cc00;">// 创建缓存线程池</span>
		ExecutorService eService02 = Executors.newCachedThreadPool();<span style="color:#33cc00;">// 内部线程个数不确定</span>

		<span style="color:#33cc00;">// 创建单一线程</span>
		ExecutorService eService03 = Executors.newSingleThreadExecutor();
<span style="color:#33cc00;">		// 如果线程池里的线程死掉,会自动创建一个新的线程来替代
/*
		eService01.shutdown();// 线程池没有任务后结束
		eService01.shutdownNow();// //线程池有任务也要结束
*/		
		//创建定时器
/*	
		ScheduledExecutorService  ses	=Executors.newScheduledThreadPool(3);
		ses.schedule(command, delay, unit);
		ses.scheduleAtFixedRate(command, initialDelay, period, unit);
*/</span>
	}

}
阻塞队列

package 线程Demo02;
<span style="color:#33cc00;">/*
 * 阻塞队列
 *      抛出异常		特殊值		阻塞		超时 
插入  add(e)       	offer(e)   	put(e)	offer(e, time, unit) 
移除  remove()   	poll()			take() 	poll(time, unit) 
检查  element() 	 	peek() 		不可用 	不可用 

 * */

/*
 * BlockingQueue
 * 
 * 例子:两个线程添加数据,一个线程取数据
 * */</span>
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueTest {
	public static void main(String[] args) {
		final BlockingQueue queue = new ArrayBlockingQueue(3);<span style="color:#33cc00;">//创建一个大小为3的对列</span>
		for(int i=0;i<2;i++){
			new Thread(){
				public void run(){
					while(true){
						try {
							Thread.sleep((long)(Math.random()*1000));
							System.out.println(Thread.currentThread().getName() + "准备放数据!");							
							queue.put(1);
							System.out.println(Thread.currentThread().getName() + "已经放了数据," + 							
										"队列目前有" + queue.size() + "个数据");
						} catch (InterruptedException e) {
							e.printStackTrace();
						}

					}
				}
				
			}.start();
		}
		
		new Thread(){
			public void run(){
				while(true){
					try {
						<span style="color:#33cc00;">//将此处的睡眠时间分别改为100和1000,观察运行结果</span>
						Thread.sleep(1000);
						System.out.println(Thread.currentThread().getName() + "准备取数据!");
					
						System.out.println(Thread.currentThread().getName() + "已经取走"+	queue.take()+"数据," + 							
								"队列目前有" + queue.size() + "个数据");					
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			
		}.start();			
	}
}







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值