java线程真的太难了!!!

         作为一个码农,你知道如何启动一个java线程吗?

启动线程方式1:

public class PrintThread extends Thread {  
   
    public void run() {  
        System.out.println("我是线程! 继承自Thread");  
    }  
    public static void main(String args[]) {  
        (new PrintThread()).start();  
    }  
} 

启动线程方式2:

public class HelloRunnable implements Runnable {  
      
    public void run() {  
        System.out.println("我也是一个线程,实现了接口");  
    }  
  
    public static void main(String args[]) {  
        (new Thread(new HelloRunnable())).start();  
    }  
  
}  

周期性任务线程 3:


/**
* 
* @author dgm
* @describe "测试打印定时器"
* @date 2017年4月10日
*/
  //注:public abstract class TimerTask implements Runnable
public class PrintTimerTask extends TimerTask {

    private String name;
    public PrintTimerTask(String name) {
        super();
        this.name = name;
    }
    @Override
    public void run() {
        if (System.currentTimeMillis( ) - scheduledExecutionTime( ) > 5000) {
            // 让下一个任务执行
            return;
        }
        System.out.println("周期性任务(好比每天早晨定闹钟)线程:"+ name +"***** 在 执行。。"); 
    }
}
public class TimeTaskTest {

    public static void main(String[] args) {
        Timer timer = new Timer();
        //设置3秒后启动任务
        timer.schedule(new PrintTimerTask("name-0"), 3000);
        PrintTimerTask secondTask = new PrintTimerTask("name-1");
        // 1秒后启动任务,以后每隔3秒执行一次线程
        timer.schedule(secondTask, 1000, 3000);
        Date date = new Date();
        // 以date为参数,指定某个时间点执行线程
        timer.schedule(new PrintTimerTask("name-3"), new Date(
                date.getTime() + 5000));
    }
}

时尚的调度器执行任务 4:

/**
 * 
 * @author dgm
 * @describe ""
 * @date 2020年4月10日
 */
public class PrintScheduledExecutor implements Runnable {

    private String jobName;

    public PrintScheduledExecutor() {

    }

    public PrintScheduledExecutor(String jobName) {
        this.jobName = jobName;
    }

    @Override
    public void run() {

        System.out.println("调度: "+ jobName + " 正在运行中!!!");
    }
}

/**
 * @author dgm
 * @describe ""
 * @date 2020年4月10日
 */
public class ScheduledThreadPoolTest {
    
    public static void main(String[] args) {
     
        ScheduledExecutorService service = Executors.newScheduledThreadPool(5);

        long initialDelay = 1;
        long period = 1;
        // ,固定频率,到期执行,从现在开始1秒钟之后,每隔1秒钟执行一次job1
        service.scheduleAtFixedRate(new PrintScheduledExecutor("job1"),
                initialDelay, period, TimeUnit.SECONDS);

        // 频率不一定固定,从现在开始2秒钟之后,每隔2秒钟执行一次job2
        service.scheduleWithFixedDelay(new PrintScheduledExecutor("job2"),
                initialDelay, period, TimeUnit.SECONDS);
    }    
}

虽然·运行良好,不建议 Executors.newScheduledThreadPool(5);,最终还是希望用这个参数明确的的方式构造线程池


 /**
     * Creates a thread pool that can schedule commands to run after a
     * given delay, or to execute periodically.
     * @param corePoolSize the number of threads to keep in the pool,
     * even if they are idle
     * @return a newly created scheduled thread pool
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
     */
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }

 /**
     * Creates a new {@code ScheduledThreadPoolExecutor} with the
     * given core pool size.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
     */
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }

 
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

参数列表简介:

 

最后一种方式参数清晰明了

 

程序虽然执行了,不过很纳闷,  start()如何启动线程的。。。。。。


 

 

其他类还有不少native方法强大无比,例如 

 

在想往下看就要有C& C++,系统方面的知识了 ,毕竟jvm是个托管的虚拟机,于java码农屏蔽了很多底层细节,底层怎么创建、调度、监视、执行线程,不是java语言多强大,确切的说而是底层很强大。

 

 

 

 

 

小结略,以后补

注: 以同步至博客园 https://www.cnblogs.com/dongguangming/p/12683579.html

和开源中国https://my.oschina.net/u/154866/blog/3230437

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值