java线程真的太难了!!!

2020-04-12 16:03:30来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

java线程真的太难了!!!

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

启动线程

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

亦或

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

又亦或周期性任务线程


/**
*
* @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));
    }
}

又亦或更时尚的调度器执行任务

/**
 * 
 * @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
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:简单工厂模式

下一篇:IDEA 正式版终于支持中文版和 JDK 直接下载了(太方便了)附介绍