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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章