java创建线程有四个方法: 1.继承Thread类 2.实现Runnable接口 3.实现Callable接口 4.创建线程池
分别用四种创建线程的方式计算1到100之间偶数的和
1.继承Thread类
public class ThreadTest {
public static void main(String[] args) {
sumTest sumTest= new sumTest();
sumTest.run();
}
}
class sumTest extends Thread{
@Override
public void run() {
int sum = 0 ;
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
sum += i;
}
}
System.out.println(sum);
}
}
2.实现Runnable接口
public class RunnableTest {
public static void main(String[] args) {
runnable1 runnable1 = new runnable1();
new Thread(runnable1).start();
}
}
class runnable1 implements Runnable {
@Override
public void run() {
int sum = 0;
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
sum += i;
}
}
System.out.println(sum);
}
}
3.实现Callable接口
public class CallableTest {
public static void main(String[] args) {
callable1 callable1 = new callable1();
//1.实例化futureTask
FutureTask futureTask = new FutureTask(callable1);
//2.将futureTask放入线程中去启动
new Thread(futureTask).start();
try {
System.out.println(futureTask.get());//3.get接收返回值(可不需要返回值)
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class callable1 implements Callable {
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
sum+= i;
}
}
return sum;//会自动装箱
}
}
4.创建线程池
public class ThreadPoll {
public static void main(String[] args) {
//1.创建线程池可容纳最多的线程数量
ExecutorService service = Executors.newFixedThreadPool(10);
//2.调用execute方法(适合用实现runnable接口的类,callable用的是submit方法)
//3.传入实现了runnable接口的类
service.execute(new threadPool());
//4.关闭连接池
service.shutdown();
}
}
class threadPool implements Runnable{
@Override
public void run() {
int sum = 0 ;
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
sum += i;
}
}
System.out.println(sum);
}
}
4.1,三种Excuutors方式
public class ThreadPool {
public static void main(String[] args) {
// ExecutorService service = Executors.newSingleThreadExecutor();//单个线程,只有一个线程在执行
// ExecutorService service = Executors.newFixedThreadPool(5);//固定线程,指定线程数
ExecutorService service = Executors.newCachedThreadPool();//可变线程数,有多少来多少
try {
for (int i = 0; i < 10; i++) {
service.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
service.shutdown();
}
}
}
4.2 但是工作一般不使用Excuutors来创建线程池
原因1:阿里创作手册上写了
原因2:看源码所得知
七大参数
例如:
4.3 调优:最大线程池该如何设计
1.CUP密集型:
最大线程数不要写死,而实根据电脑的线程数:
来设计
2.IO密集型,判断你程序中非常耗IO的进程,并且设置值为它的两倍
例如程序中15数,你就要设置最大线程数为30。