一、创建线程
1、通过继承Thread类,重写run()方法实现
public class Thread1 extends Thread{
@Override
public void run() {
try {
while (true){
Thread.sleep(1000);
System.out.println("1通过重写run方法,实现线程,线程名"+Thread.currentThread().getName()+
"线程id"+ currentThread().getId());
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public class ThreadTest1 extends Thread{
public static void main(String[] args) {
Thread1 threadt1=new Thread1();
Thread thread1 = new Thread(threadt1);
thread1.start();
Thread thread2 = new Thread() {
@Override
public void run() {
try {
while (true){
Thread.sleep(1000);
System.out.println("2通过重写run方法,实现线程,线程名"+Thread.currentThread().getName()+
"线程id"+ currentThread().getId());
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
thread2.start();
public ThreadTest1() {
super();
}
}
2、通过实现Runnable接口创建线程
public class ThreadTest1{
public static void main(String[] args) {
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true){
Thread.sleep(1000);
System.out.println("3通过重写run方法,实现线程,线程名"+Thread.currentThread().getName()+
"线程id"+ currentThread().getId());
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
thread3.start();
}
}
二、创建线程池
1、(1)创建固定的线程池,需要指定线程数;(2)利用缓存流线程池,创建可变的线程池。
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTest1 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for(int i=1;i<=10;i++){
final int task = i;
executorService.execute(new Runnable() {
@Override
public void run() {
for(int j=1;j<=10;j++){
try {
Thread.sleep(10);
System.out.println("线程的任务 = " + Thread.currentThread().getName()+" is looping of "+j+" is task of "+task);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
});
}
System.out.println("all of 10 tasks is have committed");
boolean executorServiceShutdown = executorService.isShutdown();
System.out.println("executorServiceShutdown = " + executorServiceShutdown);
}
}
2、用线程池启动定时器
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTest1 {
public static void main(String[] args) {
Executors.newScheduledThreadPool(3).schedule(new Runnable() {
@Override
public void run() {
System.out.println("bombing!");
}
},6,TimeUnit.SECONDS);
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("bombing!");
}
},6,2, TimeUnit.SECONDS);
}
}