多线程的几个小程序

火车站卖票:

public class TicketDemo extends Thread {
    static int count = 20;
    static String a = "";

    @Override
    public void run() {

        while (true) {
            try {
                //睡眠时间:循环一次,睡眠一次   --  单位:mm
                Thread.sleep(2000);
                synchronized (a) {
                    if (count > 0) {
                        System.out.println("第" + count + "张票");
                        count--;
                    } else {
                        System.out.println("卖完了");
                        System.exit(0);
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) {
        TicketDemo td = new TicketDemo();
        td.start();
        TicketDemo td1 = new TicketDemo();
        td1.start();
    }
}

文件下载

public class DownLoad extends Thread{
    private int startIndex; //线程开始下载位置
    private int endIndex; //线程结束下载位置
    private int threadId; //线程编号

    public DownLoad(int startIndex, int endIndex, int threadId) {
        this.startIndex = startIndex;
        this.endIndex = endIndex;
        this.threadId = threadId;
    }
    @Override
    public void run() {

        try {
            //统一资源管理器  ,可以直接打开 网络地址
            URL url = new URL(DownLoadTest.path);
            //获取网络请求
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置一些参数
            conn.setRequestMethod("GET");//请求方式
            conn.setConnectTimeout(5000);//链接超时
            conn.setReadTimeout(5000);//读取超时
            conn.setRequestProperty("Range","bytes="+startIndex+"-"+endIndex);//获取线程下载范围
            if(conn.getResponseCode()==206){//如果状态码为206,则显示部分数据下载完成
                //取出下载完成的链接中的数据
                InputStream is = conn.getInputStream(); //这个里面存储的是服务器上百度客户端数据
                //本地接受
                File fi = new File("BaiduNetdisk_6.9.7.4.exe");
                //输出流   ---使用的是随机读写流 rwd
                RandomAccessFile raf = new RandomAccessFile(fi,"rwd");
                //跳转到每个线程开始读取的地方
                raf.seek(startIndex);
                System.out.println("线程:"+threadId+"开始的位置"+startIndex+"--结束位置"+endIndex);
                int i = 0;
                byte[] bytes = new byte[1024];
                while ((i=is.read(bytes))!=-1){
                    raf.write(bytes,0,i);
                }
                System.out.println("下载完毕");
                raf.close();
                DownLoadTest.finishedThread ++;
                //如果全部下载完毕,则让finishedThread为0
                synchronized (DownLoadTest.path){
                    DownLoadTest.finishedThread=0;
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class DownLoadTest {
    static String path = "http://softforspeed.51xiazai.cn/down/BaiduNetdisk_6.9.7.4.exe";
    static int threadCount = 3; //3个线程
    static int finishedThread = 0;  //和 线程数 有关  ,记录每一个线程是否执行完毕

    public static void main(String[] args) {
        try {
            //打开网络地址
            URL url = new URL(DownLoadTest.path);
            //获取网络对象,与网络建立链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置一些网络参数
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);

            if(conn.getResponseCode() == 200){
            //拿到文件
                int contentLength = conn.getContentLength();
                //每个线程下载的大小
                int size = contentLength/threadCount;
                //开启线程下载
                for (int i = 0; i < threadCount; i++) {
                    int startIndex = i*size;//每个线程的开始位置
                    int endIndex = (i+1)*size;//每个线程的结束位置
                    DownLoad dl = new DownLoad(startIndex,endIndex,i);
                    dl.start();
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

多线程 求质数 返回数组中的最大值 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; }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值