关于多线程的几个小程序。。。

Semaphore 类  限制同事处理的进程数量


package duoxiancheng;

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

/**
 * Created by Administrator on 2017/12/14.
 * 排队买票 同时进行的进程数量
 */
public class SemaphoreDemo {
    class SemaphoreRunable implements Runnable{
        private Semaphore semaphore;//信号量
        private int user;//记录第几个用户

        public SemaphoreRunable(Semaphore semaphore,int user){
            this.semaphore=semaphore;
            this.user=user;
        }


        public void run() {
            try {
                //获取型号量许可
                semaphore.acquire();
                System.out.println("用户【"+user+"】进入窗口,准备买票");
                Thread.sleep((long)(Math.random()*10000));
                System.out.println("用户【"+user+"】买票完成,即将离开...");
                Thread.sleep((long)(Math.random()*10000));
                System.out.println("用户【"+user+"】离开售票窗口...");
                //释放
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    private void execute(){
        //定义窗口个数
        final Semaphore semaphore=new Semaphore(2);   //信号量 控制并发线程数
        //线程池
        ExecutorService threadPool= Executors.newCachedThreadPool();
        //模拟20个用户
        for (int i=0;i<20;i++){
            //执行买票
            threadPool.execute(new SemaphoreRunable(semaphore,(i+1)));

        }
    }
    public static void main(String[] args){
        SemaphoreDemo sd=new SemaphoreDemo();
        sd.execute();
    }
}

CountDownLatch类   等待指定数目的进程运行结束 统一进行下一步操作

package duoxiancheng;

import java.util.concurrent.CountDownLatch;
/**
 * 等待指定线程数量执行完,之后后一起进行其他操作
 * @author Administrator
 *
 */
public class CountDownLatchDemo {

    public static void main(String[] args) {
        final CountDownLatch latch= new CountDownLatch(2);
        //任务1
        new Thread(){
            public void run() {
                try {
                    System.out.println("任务1正在执行任务...");
                    Thread.sleep((long)(Math.random()*10000));
                    System.out.println("任务1执行完毕...");
                    latch.countDown();
                    
                } catch (InterruptedException e) {
    
                    e.printStackTrace();
                }
            };
        }.start();
        
        //任务2
                new Thread(){
                    public void run() {
                        try {
                            System.out.println("任务2正在执行任务...");
                            Thread.sleep((long)(Math.random()*10000));
                            System.out.println("任务2执行完毕...");
                            latch.countDown();
                            
                        } catch (InterruptedException e) {
            
                            e.printStackTrace();
                        }
                    };
                }.start();
                //主线程
                System.out.println("等待其他两个任务执行完毕,主线程才开始执行:"+Thread.currentThread().getName());
                try {
                    latch.await();//同步点  阻塞点
                    System.out.println("两个任务执行完毕:"+Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
    }

}
/*
 * 任务1正在执行任务...
等待其他两个任务执行完毕,主线程才开始执行:main
任务2正在执行任务...
任务1执行完毕...
任务2执行完毕...
两个任务执行完毕:main
*/

CyclicBarrier   统一处理结果


package duoxiancheng;

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

/**
 * Created by Administrator on 2017/12/14.
 * CyclicBarrier 可循环的障碍物
 * 多线程计算之后,最后合并结果
 */
public class CyclicBarrierDemo {
    public static void main(String[] args){
    //3个人聚餐
    final CyclicBarrier cb =new CyclicBarrier(3, new Runnable() {
        public void run() {
            System.out.println("人员全部到齐了,拍照留念。。。");
            try {
                Thread.sleep((long)(Math.random()*10000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
      //线程池
    ExecutorService threadPool= Executors.newCachedThreadPool();

//模拟3个用户
    for (int i=0;i<3;i++) {
        final int user =i+1;
        Runnable r=new Runnable() {
            public void run() {
                //模拟每个人来的时间不一样
                try {
                    Thread.sleep((long)(Math.random()*10000));
                    System.out.println(user+"到达聚餐点,当前已有"+(cb.getNumberWaiting()+1)+"人达到");
                  //阻塞
                    cb.await();
                    if(user==1){ //打印一句
                    System.out.println("拍照结束,开始吃饭...");
                    }
                    Thread.sleep((long)(Math.random()*10000));
                    System.out.println(user+"吃完饭..准备回家.");
                }catch (InterruptedException e){
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        };
        threadPool.execute(r);

    }
        threadPool.shutdown();
    }
}
/*
1到达聚餐点,当前已有1人达到
2到达聚餐点,当前已有2人达到
3到达聚餐点,当前已有3人达到
人员全部到齐了,拍照留念。。。
拍照结束,开始吃饭...
1吃完饭..准备回家.
2吃完饭..准备回家.
3吃完饭..准备回家.
*/


Exchanger 交换器


package duoxiancheng;

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

/**
 * Created by Administrator on 2017/12/14.
 */
public class ExchangerDemo {
    public static void main(String[] args){
        //交换器,交换String类型
        Exchanger<String> ec =new Exchanger<String>();
        //线程池
        ExecutorService threadPool = Executors.newCachedThreadPool();
        //张三团伙
        threadPool.execute(new Runnable() {
            public void run() {
               try {
                   String returnStr = ec.exchange("小青蛙");
                   System.out.println("绑架者用小青蛙交换回: "+returnStr);
                   
               }catch (InterruptedException e){
                   e.printStackTrace();
               }
            }
        });

        //大桥
        threadPool.execute(new Runnable() {
            public void run() {
                try {
                    String returnStr = ec.exchange("1000万");
                    System.out.println("大桥用1000万交换回: "+returnStr);

                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        threadPool.shutdown();
    }
}
/*
 * 绑架者用小青蛙交换回: 1000万
    大桥用1000万交换回: 小青蛙
*/





多线程 求质数 返回数组中的最大值 bool isPrime(long x) { if (x <= 1) return false; if (x == 2) return true; for (long i = 2; i <= ceil(sqrt((long double)x));i++) if (x%i == 0) return false; return true; } DWORD WINAPI findPrime(void* p) { long result=0; int l = stc(p)->lower, u = stc(p)->uper; int t_id=GetCurrentThreadId(); for (int i = l; i <= u;i++) if (isPrime(i)) { result++; } DWORD dReturn = WaitForSingleObject(mutex_mul_result_h, INFINITE); mul_result += result; ReleaseMutex(mutex_mul_result_h); //EnterCriticalSection(&gCRITICAL_SECTION_Printf); //printf("%d,%d,%d,%d\n", l, u, result,t_id); //fflush(stdout); //LeaveCriticalSection(&gCRITICAL_SECTION_Printf); return 0; } //dispatcher void dispatch() { DWORD Status; timer tm; tm.start(); //srand(time(NULL)); long step = STEP;//ceil(double(TEST/10)); handlenum = 0; for (int i = 1; i <= TEST;) { i += step; handlenum++; } handle_array=new HANDLE[handlenum]; Thread_id = new DWORD[handlenum ]; arg = new FP_ARG[handlenum]; InitializeCriticalSection(&gCRITICAL_SECTION_Printf); mutex_mul_result_h = CreateMutex(NULL, false, mutex_mul_result); handlenum = 0; for (int i = 1; i <= TEST;) { arg[handlenum].lower = i; arg[handlenum].uper = (i + step-1>TEST) ? TEST : i + step-1; handle_array[handlenum]=(HANDLE)CreateThread(NULL, 0, findPrime, &arg[handlenum], 0, &Thread_id[handlenum]); /*EnterCriticalSection(&gCRITICAL_SECTION_Printf); printf("lower:%d uper:%d thread_id:%d\n", arg[handlenum].lower, arg[handlenum].uper,Thread_id[handlenum]); LeaveCriticalSection(&gCRITICAL_SECTION_Printf);*/ i += step; handlenum++; } tm.stop(); Sleep(1000); printf("there are %d threads\n", handlenum); printf("the multithreads use %f msc\n", tm.read()); } //the number of 1-1000000 Primenumber void s_finePrime() { timer tm; long result = 0; tm.start(); for (int i = 1; i <= TEST; i++) if (isPrime(i)) result++; tm.stop(); printf("Single thread result is %d\n", result); printf("Single thread use %f msc\n", tm.read()); } int _tmain(int argc, _TCHAR* argv[]) { dispatch(); WaitForMultipleObjects(handlenum, handle_array, true, INFINITE);//不起作用 printf("the multithreads reslut is %d\n", mul_result); CloseHandle(mutex_mul_result_h); DeleteCriticalSection(&gCRITICAL_SECTION_Printf); s_finePrime(); system("pause"); return 0; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值