java并发编程实践 part 01 --> 线程创建方式

简介: 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26654727/article/details/78013989 最近在尝试重新复习一段关于多线程的使用,同时尝试使用关于markdown编辑器的使用方法,会同步将自己整理的文档放上来。
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26654727/article/details/78013989

最近在尝试重新复习一段关于多线程的使用,同时尝试使用关于markdown编辑器的使用方法,会同步将自己整理的文档放上来。

线程创建方式

通过创建一个线程类的方式创建线程体,例如实现runnable接口创建一个实现类。或者是直接通过创建Thread方式,重写内部的runnable方法实现线程体的编写。

1. 接用Thread.start 的方式进行重写runnable的方式进行实现线程。 继承Thread创建线程

new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    System.out.println("just a test " + Thread.currentThread().getName()+ " "+new Date());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

输出结果:
just a test Thread-0 Sun Sep 17 09:48:48 CST 2017
just a test Thread-0 Sun Sep 17 09:48:49 CST 2017
just a test Thread-0 Sun Sep 17 09:48:50 CST 2017
just a test Thread-0 Sun Sep 17 09:48:51 CST 2017
just a test Thread-0 Sun Sep 17 09:48:52 CST 2017
just a test Thread-0 Sun Sep 17 09:48:53 CST 2017

2.创建一个实现Runnable接口并重写run方式的实现类,来进行线程体逻辑的可重用。

public class CreatThread02 implements  Runnable{
    @Override
    public void run() {
        System.out.println("currentThread : "+ Thread.currentThread().getName()+ "  say hello for you ... time --> " + new Date());
    }

    public static void main(String[] args) {
        Runnable thread01 = new CreatThread02();
        Runnable thread02 = new CreatThread02();

        while (true){
            try {
                thread01.run();
                Thread.sleep(500);
                thread02.run();
                Thread.sleep(400);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }
}

输出结果:
currentThread : main  say hello for you ... time --> Sun Sep 17 10:02:45 CST 2017
currentThread : main  say hello for you ... time --> Sun Sep 17 10:02:45 CST 2017
currentThread : main  say hello for you ... time --> Sun Sep 17 10:02:46 CST 2017
currentThread : main  say hello for you ... time --> Sun Sep 17 10:02:46 CST 2017
currentThread : main  say hello for you ... time --> Sun Sep 17 10:02:46 CST 2017
currentThread : main  say hello for you ... time --> Sun Sep 17 10:02:47 CST 2017

3.通过创建线程池的方式创建线程

  public static void main(String[] args) {

        ExecutorService service = Executors.newFixedThreadPool(2);
        for(int i = 0 ; i< 100 ;i++){
            RunClass run = new RunClass(i);
            service.execute(run);

        }

        service.shutdown();

    }



    static class RunClass  implements  Runnable{

        private int index ;

        public RunClass(int index ){
            this.index = index;
        }

        @Override
        public void run() {
           long sleeptime = (long)(Math.random()*1000);
            System.out.println("the RunClassNum-->  "+index +"  cunrrentThread -->  "+ Thread.currentThread().getName()+ " come back over ..." + " Sleep Time -->" +sleeptime);

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

输出结果:
the RunClassNum-->  87  cunrrentThread -->  pool-1-thread-2 come back over ... Sleep Time -->152
the RunClassNum-->  88  cunrrentThread -->  pool-1-thread-2 come back over ... Sleep Time -->207
the RunClassNum-->  89  cunrrentThread -->  pool-1-thread-2 come back over ... Sleep Time -->958
the RunClassNum-->  90  cunrrentThread -->  pool-1-thread-1 come back over ... Sleep Time -->484
the RunClassNum-->  91  cunrrentThread -->  pool-1-thread-1 come back over ... Sleep Time -->767
the RunClassNum-->  92  cunrrentThread -->  pool-1-thread-2 come back over ... Sleep Time -->202
the RunClassNum-->  93  cunrrentThread -->  pool-1-thread-2 come back over ... Sleep Time -->666
the RunClassNum-->  94  cunrrentThread -->  pool-1-thread-1 come back over ... Sleep Time -->454
Executors类中存在多个线程池类型,具体分为以下几种:
  • public static ExecutorService newFixedThreadPool(int nThreads) :
    可创建指定数量线程的线程池,当有新的线程需要执行,同时线程池内有空余线程,则会直接取用当前空闲线程,来达到线程的利用率。
  • public static ThreadFactory defaultThreadFactory();
    返回线程池的默认线程创建工厂
  • public static ExecutorService newCachedThreadPool();
    创建一个线程池,根据需要适当的创建线程的方式,

4.线程的控制 sleep、join、interrupt

  • sleep–>使当前线程暂停一段时间
  • join–>使当前的线程加入另一个线程
public class Controller4Thread01 extends Thread {

//    1.使用sleep使当前线程暂停一段时间
//    2.使用join是当前线程加入另一个线程
    public static int result;

    public Controller4Thread01(String name ){
        super(name);
    }


    @Override
    public void run() {
        result = (int)( Math.random()*1000);

        System.out.println("currentThread name-->"+ this.getName() + " get result -->" + result);

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

    public static void main(String[] args) {
        Controller4Thread01 thread01 = new Controller4Thread01("测试线程1");
        thread01.start();
        long startTime = System.currentTimeMillis();
        System.out.println("开始时间为--> " + startTime);
        System.out.println("thread 未加入之前 ..  result-->"+result);
        try {

            thread01.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("结束时间为--> "+ endTime + " 时间间隔-->" + (endTime-startTime));
    }
}

输出结果:
  • interrupt–>打断当前的线程
public class Controller4Thread01 extends Thread {

//    1.使用sleep使当前线程暂停一段时间
//    2.使用join是当前线程加入另一个线程
//    3.使用interrupt打断线程
    public static int result;
    public long time ;

    public Controller4Thread01(String name ){
        super(name);
    }


    @Override
    public void run() {
        long starttime = System.currentTimeMillis();
        try {
            result = (int)( Math.random()*1000);
            System.out.println("currentThread name-->"+ this.getName() + " get result -->" + result);
            Thread.sleep(4000);
            long endTime = System.currentTimeMillis();
            time = endTime-starttime;
            System.out.println(this.getName() + "--> 线程正常运行,且当前线程已运行时间 --> "+ time + "ms");
        } catch (InterruptedException e) {
            long endTime = System.currentTimeMillis();
            time = endTime-starttime;
            System.out.println(this.getName() + "--> 线程被中断,且当前线程已运行时间 --> "+ time + "ms");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Controller4Thread01 thread01 = new Controller4Thread01("测试线程1");
        thread01.start();
        long startTime = System.currentTimeMillis();
        System.out.println("开始时间为--> " + startTime);
        System.out.println("thread 未加入之前 ..  result-->"+result);
        try {
            thread01.join(2000);
            long endTime = System.currentTimeMillis();
            thread01.interrupt();
            System.out.println("结束时间为--> "+ endTime + " 时间间隔-->" + (endTime-startTime));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
//输出结果:
开始时间为--> 1505642692997
thread 未加入之前 ..  result-->0
currentThread name-->测试线程1 get result -->648
结束时间为--> 1505642694998 时间间隔-->2001
java.lang.InterruptedException: sleep interrupted
测试线程1--> 线程被中断,且当前线程已运行时间 --> 2000ms
    at java.lang.Thread.sleep(Native Method)
    at Thread.threadConcurrency01.Part02.Controller4Thread01.run(Controller4Thread01.java:22)

若有希望一起交流的朋友可以加我的有道云笔记的群,大家互相整理的技术栈。仅为交流 –>

(群号:51920822) –> http://163.fm/QO0DihJw

目录
相关文章
|
11月前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
919 0
|
11月前
|
Java
如何在Java中进行多线程编程
Java多线程编程常用方式包括:继承Thread类、实现Runnable接口、Callable接口(可返回结果)及使用线程池。推荐线程池以提升性能,避免频繁创建线程。结合同步与通信机制,可有效管理并发任务。
387 6
|
11月前
|
JSON 网络协议 安全
【Java】(10)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
568 1
|
11月前
|
JSON 网络协议 安全
【Java基础】(1)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
494 1
|
数据采集 存储 弹性计算
高并发Java爬虫的瓶颈分析与动态线程优化方案
高并发Java爬虫的瓶颈分析与动态线程优化方案
Java 数据库 Spring
515 0
|
算法 Java
Java多线程编程:实现线程间数据共享机制
以上就是Java中几种主要处理多线程序列化资源以及协调各自独立运行但需相互配合以完成任务threads 的技术手段与策略。正确应用上述技术将大大增强你程序稳定性与效率同时也降低bug出现率因此深刻理解每项技术背后理论至关重要.
676 16
|
缓存 并行计算 安全
关于Java多线程详解
本文深入讲解Java多线程编程,涵盖基础概念、线程创建与管理、同步机制、并发工具类、线程池、线程安全集合、实战案例及常见问题解决方案,助你掌握高性能并发编程技巧,应对多线程开发中的挑战。
|
数据采集 存储 前端开发
Java爬虫性能优化:多线程抓取JSP动态数据实践
Java爬虫性能优化:多线程抓取JSP动态数据实践
|
Java API 调度
从阻塞到畅通:Java虚拟线程开启并发新纪元
从阻塞到畅通:Java虚拟线程开启并发新纪元
572 83