Java多线程练习小记

Java多线程练习

两个线程轮流打印数字,一直到100

public class HomeWork1 implements Runnable {

    // 操作全局变量
    private Integer num = 0;

    @Override
    public synchronized void run() {
        while (true) {
            // 对要同步的 代码块 加锁
            //            synchronized (this) {
            // 唤醒一个线程
            notify();
            if (num <= 100) {
                //                try {
                // 线程睡眠 10毫秒
                //                    Thread.sleep(30);
                //                } catch (InterruptedException e) {
                //                    e.printStackTrace();
                //                }
                System.out.println(Thread.currentThread().getName() + "  -->  " + num);
                num++;
                try {
                    // 当前线程打印完以后等待,等待被下一个线程唤醒
                    wait();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                break;
                //                }
            }
        }
    }
}

三个窗口同时卖票 用 实现Runnable方式

package club.gskj.demo4;

/**
 * @author : Connor-G 康纳-郭
 * @date : 17:38 20.7.20
 * @Company : http://www.gskj.club
 * @Version : 1.0
 */

public class TickerDemo implements Runnable {

    private Integer ticket = 100;

    @Override
    public synchronized void run() {

        while (true) {
            // 同步代码块
            //            synchronized (this) {
            // 唤醒所有正在等待的线程
            notifyAll();
            if (ticket > 0) {

                //                try {
                //                    Thread.sleep(10);
                //                } catch (InterruptedException e) {
                //                    e.printStackTrace();
                //                }

                System.out.println(Thread.currentThread().getName() + " ---> " + ticket + " 号票 已卖出 ,还剩余 " + --ticket + " 票");
                try {
                    // 当前线程等待
                    wait();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // 跳出循环
                break;
                //                }
            }
        }
    }

    public static void main(String[] args) {

        Runnable r = new TickerDemo();

        new Thread(r).start();
        new Thread(r).start();
        new Thread(r).start();
    }
}

java多线程实现 文件下载功能

package club.gskj.demo2;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author : Connor-G 康纳-郭
 * @date : 16:12 20.7.20
 * @Company : http://www.gskj.club
 * @Version : 1.0
 */

public class MathchDome extends Thread {

    private Integer startIndex; // 开始下载位置
    private Integer endIndex; // 下载结束位置
    private Integer name; //  线程名称

    public MathchDome(Integer startIndex, Integer endIndex, Integer name) {
        this.startIndex = startIndex;
        this.endIndex = endIndex;
        this.name = name;
    }

    // 重写 run方法
    @Override
    public void run() {

        InputStream is = null;
        RandomAccessFile raf = null;
        try {
            // 创建资源对象
            URL uploadUrl = new URL(MtachDemoTest.dowLoadUrl);
            // 使用子类 Http接受
            HttpURLConnection connection = (HttpURLConnection) uploadUrl.openConnection();

            // 请求方式
            connection.setRequestMethod("GET");
            // 读取超时时间
            connection.setReadTimeout(5000);
            // 超时时间
            connection.setConnectTimeout(5000);
            // 设置 使用缓存
            connection.setUseCaches(true);

            // 设置请求头 分批下载
            connection.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);

            // 获取服务器响应码
            int responseCode = connection.getResponseCode();

            // 下载文件的相对路径
            File file = new File("BaiduNetdisk_6.9.7.4.exe");
            // 部分数据 ok
            if (206 == responseCode) {

                // 获取 输入流
                is = connection.getInputStream();

                // 创建 随机读取文件流
                raf = new RandomAccessFile(file, "rwd");
                // 每次跳转到 指定开始位置
                raf.seek(startIndex);
                System.out.println(" 当前位置: " + startIndex + " 结束位置: " + endIndex + " 线程名称: " + name);

                // 读写操作
                int len = 0;
                byte[] buffer = new byte[1024];

                while ((len = is.read(buffer)) != -1) {
                    raf.write(buffer, 0, len);
                }
                System.out.println("当前线程: " + name + " 下载完毕");

                // 当前记录线程数量自增
                MtachDemoTest.threadNum++;

                synchronized (MtachDemoTest.threadNum) {
                    MtachDemoTest.threadNum = 0;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭资源
                raf.close();
                is.close();
            } catch (Exception e) {

            }
        }
    }
}

测试类

package club.gskj.demo2;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author : Connor-G 康纳-郭
 * @date : 16:20 20.7.20
 * @Company : http://www.gskj.club
 * @Version : 1.0
 */

public class MtachDemoTest {

    static Integer threadCount = 3; // 总共线程数量
    static Integer threadNum = 0; // 记录当前线程数量
    static String dowLoadUrl = "http://softforspeed.51xiazai.cn/down/BaiduNetdisk_6.9.7.4.exe";


    public static void main(String[] args) {

        try {
            // 创建资源对象
            URL uploadUrl = new URL(MtachDemoTest.dowLoadUrl);
            // 使用子类 Http接受
            HttpURLConnection connection = (HttpURLConnection) uploadUrl.openConnection();

            connection.setRequestMethod("GET");
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setUseCaches(true);

            if (connection.getResponseCode() == 200) {
                // 获取资源文件 总长度
                int contentLength = connection.getContentLength();

                for (int i = 0; i < threadCount; i++) {

                    // 计算出 每个线程分配多少 资源
                    // 文件总数
                    int size = contentLength / threadCount;

                    //开始位置
                    int startIndex = i * size;
                    // 结束位置
                    int endIndex = (i + 1) * size;

                    // 创建线程
                    MathchDome mathchDome = new MathchDome(startIndex, endIndex, +i);
                    // 开启线程
                    mathchDome.start();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }
}
原文地址:https://www.cnblogs.com/mt-blog/p/13346731.html