作为一个码农,你知道如何启动一个java线程吗?
启动线程
public class PrintThread extendsThread {public voidrun() {
System.out.println("我是线程! 继承自Thread");
}public static voidmain(String args[]) {
(newPrintThread()).start();
}
}
亦或
public class HelloRunnable implementsRunnable {public voidrun() {
System.out.println("我也是一个线程,实现了接口");
}public static voidmain(String args[]) {
(new Thread(newHelloRunnable())).start();
}
}
又亦或周期性任务线程
/**
*
* @author dgm
* @describe "测试打印定时器"
* @date 2017年4月10日
*/
//注:public abstract class TimerTask implements Runnable
public class PrintTimerTask extendsTimerTask {privateString name;publicPrintTimerTask(String name) {super();this.name =name;
}
@Overridepublic voidrun() {if (System.currentTimeMillis( ) - scheduledExecutionTime( ) > 5000) {//让下一个任务执行
return;
}
System.out.println("周期性任务(好比每天早晨定闹钟)线程:"+ name +"***** 在 执行。。");
}
}
public classTimeTaskTest {public static voidmain(String[] args) {
Timer timer= newTimer();//设置3秒后启动任务
timer.schedule(new PrintTimerTask("name-0"), 3000);
PrintTimerTask secondTask= new PrintTimerTask("name-1");//1秒后启动任务,以后每隔3秒执行一次线程
timer.schedule(secondTask, 1000, 3000);
Date date= newDate();//以date为参数,指定某个时间点执行线程
timer.schedule(new PrintTimerTask("name-3"), newDate(
date.getTime()+ 5000));
}
}
又亦或更时尚的调度器执行任务
/***
*@authordgm
* @describe ""
* @date 2020年4月10日*/
public class PrintScheduledExecutor implementsRunnable {privateString jobName;publicPrintScheduledExecutor() {
}publicPrintScheduledExecutor(String jobName) {this.jobName =jobName;
}
@Overridepublic voidrun() {
System.out.println("调度: "+ jobName + " 正在运行中!!!");
}
}
/***@authordgm
* @describe ""
* @date 2020年4月10日*/
public classScheduledThreadPoolTest {public static voidmain(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.
*@paramcorePoolSize the number of threads to keep in the pool,
* even if they are idle
*@returna newly created scheduled thread pool
*@throwsIllegalArgumentException if {@codecorePoolSize < 0}*/
public static ScheduledExecutorService newScheduledThreadPool(intcorePoolSize) {return newScheduledThreadPoolExecutor(corePoolSize);
}/*** Creates a new {@codeScheduledThreadPoolExecutor} with the
* given core pool size.
*
*@paramcorePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@codeallowCoreThreadTimeOut} is set
*@throwsIllegalArgumentException if {@codecorePoolSize < 0}*/
public ScheduledThreadPoolExecutor(intcorePoolSize) {super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,newDelayedWorkQueue());
}public ThreadPoolExecutor(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime,
TimeUnit unit,
BlockingQueueworkQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {if (corePoolSize < 0 ||maximumPoolSize<= 0 ||maximumPoolSize< corePoolSize ||keepAliveTime< 0)throw newIllegalArgumentException();if (workQueue == null || threadFactory == null || handler == null)throw newNullPointerException();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语言多强大,确切的说而是底层很强大。
小结略,以后补