线程和线程池的使用
Posted 从零学java开发
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程和线程池的使用相关的知识,希望对你有一定的参考价值。
public class ThreadDemo {
public static void main(String[] args) {
//这里是主线程
MyThread myThread = new MyThread();
//创建线程
Thread thread = new Thread(myThread);
//开启线程
thread.start();
//从这里开始主线程
// 和mythread子线程同时运行
// 2个线程各自执行自己的,互不干扰
for (int i = 0 ; i < 100 ; i++)
System.out.println(Thread.currentThread().getName() + "main主线程运行");
}
}
class MyThread implements Runnable{
@Override
public void run() {
for (int i = 0 ; i < 100 ; i++){
System.out.println(Thread.currentThread().getName() + "mythread子线程运行");
}
}
}
public class RunnableDemo {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100 ; i++)
System.out.println(Thread.currentThread().getName() + "mythread子线程运行");
}}).start();
//从这里开始,2个线程同时执行
for (int i = 0 ; i < 100 ; i++)
System.out.println(Thread.currentThread().getName() + "main主线程运行");
}
}
public static void main(String[] args) {
new Thread(() -> {
for (int i = 0 ; i < 100 ; i++)
System.out.println(Thread.currentThread().getName() + "mythread子线程运行");
}).start();
//从这里开始,2个线程同时执行
for (int i = 0 ; i < 100 ; i++)
System.out.println(Thread.currentThread().getName() + "main主线程运行");
}
public class ThreadPoolDemo {
public static void main(String[] args) {
//核心线程数
int corePoolSize = 5;
//最大线程数
int maxPoolSize = 10;
//空闲线程存活时间
int keepAliveTime = 60;
//存活时间的单位
TimeUnit unit = TimeUnit.SECONDS;
//阻塞队列
BlockingQueue blockQueue = new LinkedBlockingQueue<Runnable>();
//拒绝策略
ThreadPoolExecutor.AbortPolicy abortPolicy = new ThreadPoolExecutor.AbortPolicy();
ThreadPoolExecutor threadPool = new ThreadPoolExecutor
(corePoolSize, maxPoolSize, keepAliveTime, unit, blockQueue, abortPolicy);
//把任务加进线程池,并执行任务执行任务
threadPool.execute(new MyThread());
}
static class MyThread implements Runnable{
public void run() {
for (int i = 0 ; i < 100 ; i++)
System.out.println(Thread.currentThread().getName() + "mythread子线程运行");
}
}
}
threadPool.allowCoreThreadTimeOut(true);
以上是关于线程和线程池的使用的主要内容,如果未能解决你的问题,请参考以下文章