线程默认优先级为5,总是main所在的主线程先执行,因为main是程序的入口。
1.继承Thread 重写run 方法
MyThread myThread = new MyThread();
myThread.start();
2.实现Runnable接口 实现run方法
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable,"runnable1");
thread.start();
3.实现Callable 接口 实现call方法,然后把 MyCallable 交给Futuretask,然后task 再交给Thread
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int i = 0;
for (; i <= 10; i++) {
System.out.println(Thread.currentThread().getName() + "..." + i);
}
return i;
}
}
public class TestCallable {
public static void main(String[] args) {
MyCallable myCallable = new MyCallable();
FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
Thread thread = new Thread(futureTask, "callable1");
thread.start();
for(int i=0;i<10;i++){
System.out.println(i + " , main");
}
}
}
5.通过线程池创建线程实例
1. newFixedThreadPool
使用于为了满足资源管理需求而需要限制当前线程数量的场合。使用于负载比较重的服务器。
public static void main(String[] args) {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);//固定大小的线程池
for (int j = 0; j < 5; j++) {
fixedThreadPool.submit(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " , " + Thread.currentThread().getName());
}
}
});
}
fixedThreadPool.shutdown();
}
2.newSingleThreadExecutor 需要保证顺序执行各个任务的场景
public static void main(String[] args) {
ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();//单线程池,需要保证顺序执行各个任务的场景
for (int i = 0; i < 10; i++) {
singleThreadPool.submit(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " , " + Thread.currentThread().getName());
}
}
});
}
}
3. newCachedThreadPool()缓存线程池
当提交任务速度高于线程池中任务处理速度时,缓存线程池会不断的创建线程
适用于提交短期的异步小程序,以及负载较轻的服务器。
public static void main(String[] args) {
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();//单线程池,需要保证顺序执行各个任务的场景
for (int i = 0; i < 10; i++) {
cachedThreadPool.submit(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " , " + Thread.currentThread().getName());
}
}
});
}
}
还有其他方法创建线程,请大家自行搜索。谢谢大家。