实例代码摘录_生产消费、死锁

生产者消费者

Java多线程之生产者与消费者
***********************核心方法类****************
package test.com;
class Queue
// key
{
int value;
boolean bFull = false;
public synchronized void put(int i) {
if (!bFull) {
value = i;
bFull = true;
notify();// 必须用在synchronized
}
try {
wait();// 必须捕获异常
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized int get() {
if (!bFull)
try {
wait();//进入
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bFull = false;
notify();
return value;
}
}

************************生产者类********************************
package test.com;
class Producter extends Thread
{
Queue q;
Producter (Queue q)
{
this.q=q;
}
public void run()
{
System.out.println(“********producter****start*****”);
for(int i=1;i《10;i++)
{
System.out.println(“producter :”+i);
q.put(i);
}
System.out.println(“********producter*****end****”);
}
}
**********************************************************************
****************************消费者类*********************************
package test.com;
class Consumer extends Thread
{
Queue q;
Consumer(Queue q)
{
this.q=q;
}
public void run()
{
System.out.println(“********Consumer****start*****”);
while(true)
{
System.out.println(“Consumer:”+q.get());
System.out.println(“********Consumer****end*****”);
}
}
}
************************************************************************
*******************************主函数调用类**********************************
package test.com;
public class Test {
public static void main(String[] args) {
Queue q=new Queue();
Producter p=new Producter(q);
Consumer c=new Consumer(q);
p.start();
c.start();
}}
*****************************************************************
OK,实现完毕
wait方法——把线程放入wait set
notify方法——从wait set拿出线程
notifyAll方法——从wait set拿出所有线程
wait、notify、notifyAll是Object类的方法

死锁

package dead;


class Lock implements Runnable{
	public Boolean flag;
	public Lock(Boolean flag) {
		this.flag = flag;
	}
	static Object lock1 = new Object();
	static Object lock2 = new Object();
	
	public void run() {
		
		if(flag){
			while(true){
				synchronized (lock1) {
					System.out.println("if lock1");
					synchronized (lock2) {
						System.out.println("if lock2");
					}
				}
			}
			
		}else {
			while(true){
				synchronized (lock2) {
					System.out.println("else if lock2");
					synchronized (lock1) {
						System.out.println("else if lock1");
					}
				}
			}
		}
	}
	
}

public class DeadLock {
	public static void main(String[] args){
		Lock fg1 = new Lock(true);
		Lock fg2 = new Lock(false);
		Thread t1 = new Thread(fg1);
		Thread t2 = new Thread(fg2);
		t1.start();
		t2.start();
		
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值