多线程实例

1. 多个窗口同时卖票,利用多线程模拟售票程序
package com.cnwir.test;

public class SaleTicket {
    public static void main(String[] args) {
        Ticket ticket =new Ticket(20);
        for (int i = 0; i < 5; i++) {//5个线程
            new Thread(new Seller(ticket),String.valueOf(i)).start();//线程启动
        }
    }
}
/**
 * 卖票线程类
 * @author administrator
 *
 */
class Seller implements Runnable{
    Ticket ticket;
    public Seller(Ticket ticket) {
        // TODO Auto-generated constructor stub
        this.ticket =ticket ;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (ticket.has) {//如果有票继续售,否则终止售票
            ticket.sellerTicket();//
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
/**
 * 定义票信息类
 * @author administrator
 *
 */
class Ticket {
    private int ticketCount;
    protected boolean has=true ;//是否有票
    public Ticket(int ticketCount) {
        // TODO Auto-generated constructor stub
        this.ticketCount=ticketCount;
    }
    public synchronized void sellerTicket() {
        if(ticketCount>0){
            System.out.println(Thread.currentThread().getName()+"窗口卖第"+ticketCount+"张票");
            ticketCount--;
        }else{
            System.out.println("票已经售完!");
            has=false;//票已售完
        }
    }
    
}//end
2.生产者和消费者的多线程例子
     情景模式:消费者(Custom)要在一个盒子里面消费东西,生存者(Product)要把生产好的东西放在盒子里面,如果盒子里面没有东西消费者是不能取东西,生产者生产好了通知(notify)消费者可以在盒子里面拿东西了,
此时盒子有东西不能生产,生产者要等待(wait);当消费者拿了之后通知(notify)生产者,我把盒子里面的东西拿了,盒子空了你去生产吧,要等待(wait)生产者生产。
package com.cnwir.test;

public class ThreadBox {
    private int content ;//产品
    private boolean has ;//标识盒子是否有东西
    public static void main(String[] args) {
    ThreadBox box =new ThreadBox();
    Thread pro =new Thread(new Product(box),"生产者");
    Thread cus =new Thread(new Custom(box),"消费者");
    pro.start();
    cus.start();
    }
    //生产好的添加到盒子里面
    public synchronized void setContent(int content) {
        if(has){
            try {
                wait();//盒子有东西就等待
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        has=true;
        notify();
        this.content = content;
    }
    public synchronized int getContent() {
        if(has==false){
            try {
                wait();//盒子没有东西等待
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        has=false;
        notify();//通知生产者,盒子没有东西了
        return content;
    }
}
class Product implements Runnable{
    private int content =1;
    ThreadBox box;
    public Product(ThreadBox box) {
        // TODO Auto-generated constructor stub
        this.box=box;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
    while (true) {
        System.out.println("已生产的商品->"+content);
        box.setContent(content);
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        content++;
    }
    }
    
}
class Custom  implements Runnable{
    ThreadBox box;
    public Custom(ThreadBox box) {
        // TODO Auto-generated constructor stub
        this.box=box;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
    while (true) {
        System.out.println("已消费的商品->"+box.getContent());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    }   
}//end
3.生产者消费者模式实践
  情景模式:阻塞队列blockingquque的公平性在于先阻塞的生产者可以先put,先阻塞的消费者可以先take,这样做降低了吞吐量,
而锁的公平性在于,访问临界区代码时,aqs维护的当前node之前是否还有其他node,如果有则不会获取锁,一定程度上保证了公平性但是,和操作系统调度不匹配,本该获取缺放弃了锁一定程度上降低了效率!
package com.cnwir.test;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

public class ArrayBlockingQueueTest {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        BlockingQueue<TestBean> testBeanBlockingQueue = new ArrayBlockingQueue<TestBean>(100,true);
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.submit(new Producer(testBeanBlockingQueue,lock));
        executorService.submit(new Consumer(testBeanBlockingQueue,lock));
        executorService.submit(new Consumer(testBeanBlockingQueue,lock));
        executorService.submit(new Consumer(testBeanBlockingQueue,lock));
        executorService.submit(new Consumer(testBeanBlockingQueue,lock));
        executorService.shutdown();
    }
}
class Producer implements  Runnable{
    private BlockingQueue<TestBean> queue;
    private static ReentrantLock lock;
    Producer(BlockingQueue<TestBean> queue,ReentrantLock lock) {
        this.queue = queue;
        this.lock = lock;
    }
    @Override
    public void run() {
        while(true){
            try {
                TestBean testBean = new TestBean("testbean");
                //synchronized (queue){
                    try{
                        lock.lock();
                        queue.put(testBean);
                        System.out.println("放入了" + testBean.getName());
                    }finally {
                        lock.unlock();
                    }
                //}
                if(TestBean.count.get() == 10) break;
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
    }
}
class Consumer implements  Runnable{
    private BlockingQueue<TestBean> queue;
    private static ReentrantLock lock;// = new ReentrantLock();
    Consumer(BlockingQueue<TestBean> queue,ReentrantLock lock) {
        this.queue = queue;
        this.lock = lock;
    }
    @Override
    public void run() {
        try {
            while(true){
                //synchronized (queue){
                    //为了避免消费者先于生产者执行从而造成take阻塞,永远无法释放quque造成死锁,操作系统并不完全保证线程执行公平性
                try{
                    lock.lock();
                    if(queue.size() == 0){
                        continue;
                    }
                    TestBean testBean = queue.take();
                    System.out.println("取出了" + testBean.getName());
                }finally {
                    lock.unlock();
                }
                //}
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }
}

package com.cnwir.test;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * Created by Administrator on 14-5-13.
 */
public class TestBean {
    private String name;
    public static AtomicInteger count = new AtomicInteger(0);
    public TestBean(String name) {
        this.name = name + count.getAndAdd(1);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}


你可能感兴趣的:(多线程实例)