JavaEE____多线程1

文章目录

  • 一. 线程使用
    • 1. 线程休眠演示打印电影字幕
    • 2.多线程性能 VS 单线程性能
      • 2.1单线程执行时间
      • 2.2 多线程执行时间
    • 3.线程3种创建方式
      • 3.1创建方式1:继承Thread
        • a) 使用 jconsole 观察线程
        • b) 启动线程——start方法
      • 3.2创建方式2:实现Runnable接口(4种写法)
        • 3.2.1 写法1
        • 3.2.2 写法2
        • 3.2.3 写法3
        • 3.2.4 写法4
      • 3.3创建方式3:实现 Callable 接口进行实现(2种写法)
        • 3.3.1 Callable+Future
        • 3.3.2

一. 线程使用

1. 线程休眠演示打印电影字幕

/*
* 使用线程实现电影旁白的打印
* */
public class ThreadDemo1 {
   
    public static void main(String[] args) throws InterruptedException {
   
        String content = "想把我唱给你听,趁现在年少如花";
        for (char item : content.toCharArray()){
   
            System.out.print(item);
            Thread.sleep(250);
        }

    }
}

2.多线程性能 VS 单线程性能

2.1单线程执行时间

public class ThreadDemo2 {
   
    private final static  int COUNT = 10;
    public static void main(String[] args) {
   
        //记录开始时间
        long stime = System.currentTimeMillis();

        //使用单线程执行
        singleThread();

        //记录结束时间
        long etime = System.currentTimeMillis();
        System.out.println("单线程执行时间:" + (etime - stime));
    }

    /*
    * 单线程任务执行
    * */
    private static void singleThread(){
   

        for (int i = 0; i < COUNT ; i++) {
   
            //每次方法执行需要一秒
            try {
   
                Thread.sleep(1000);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
        }
    }

}

JavaEE____多线程1_第1张图片

你可能感兴趣的:(JavaEE,java-ee)