记录一个基础线程的创建

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27376871/article/details/82783430

线程池负责管理工作线程,包含一个等待执行的任务队列。线程池的任务队列是一个Runnable集合,工作线程负责从任务队列中取出并执行Runnable对象。下面是一个简单示例:

首先创建一个Runable 类:

public class ThreadPoolTest extends Thread{


    //写一个类执行十次随机时间休眠
    @Override
    public void run() {
        try {
            for (int i = 0; i < 10; i++) {
                int time = (int) (Math.random() * 1000);
                Thread.sleep(time);
                System.out.println("当前线程是  " + Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    /**
     * 创建基础线程
     */
    static void newThread() {
        try {
            ThreadPoolTest thread = new ThreadPoolTest();
            thread.setName("new Thread");
            thread.start();
            for (int i = 0; i < 10; i++) {
                final int index = i;
                int time = (int) (Math.random() * 1000);
                Thread.sleep(time);
                System.out.println("当前线程是  " + Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
public static void main(String[] args) {
    newThread();
}

}

输出结果:

当前线程是  main
当前线程是  new Thread
当前线程是  new Thread
当前线程是  new Thread
当前线程是  main
当前线程是  new Thread
当前线程是  main
当前线程是  main
当前线程是  main
当前线程是  new Thread
当前线程是  main
当前线程是  main
当前线程是  new Thread
当前线程是  new Thread
当前线程是  main
当前线程是  new Thread
当前线程是  main
当前线程是  new Thread
当前线程是  new Thread
当前线程是  main
 

猜你喜欢

转载自blog.csdn.net/qq_27376871/article/details/82783430
今日推荐