多线程之创建线程的方式
继承Thread类
1.新建一个线程类继承Thread类
2.重写run()
3.在main方法中实例化线程对象
4.调用start()
public class Thread01{
public static void main(String []args){
MyThread t = new MyThread();
t.start();
for(int i = 0;i < 100;i++){
System.out.println("main");
}
}
}
class MyThread extends Thread{
@Override
public void run(){
for(int i = 0;i < 100;i++){
System.out.println("MyThread");
}
}
}
实现Runnable接口
1.创建线程类并实现Runnable接口
2.实现run()
3.在main线程中实例化线程类创建对象
4.实例化Thread,将线程类对象作为参数放入Thread构造器中
4.调用start()
public class Thread02{
public static void main(String []args){
MyThread02 runnable01 = new MyThread02();
Thread t2 = new Thread(runnable01);
t2.start();
for(int i = 0;i < 100; i++){
System.out.println("main");
}
}
}
class MyThread02 implements Runnable{
public void run(){
for(int i = 0;i < 100; i++){
System.out.println("Runnable");
}
}
}
实现Callable接口:
1.创建自定义线程类实现Callable接口
2.实现call方法
3.在main方法中创建自定义线程类的对象,
将此对象作为参数传递到FutureTask构造器中,创建FutureTask对象
4.将FutureTask对象作为参数传递到Thread构造器中,
创建Thread对象
5.调用Thread对象的start方法启动线程
6.接收call方法的返回值(如果存在返回值)
public class Thread_Callable{
public static void main(String []args){
MyCallable c = new MyCallable();
FutureTask f = new FuthreTask(c);
Thread t = new Thread(f);
t.start();
Object sum = f.get();
System.out.println(sum);
}
}
class MyCallable implements Callable{
public Object run(){
for(int i = 1;i <= 100; i++){
System.out.println(i);
count+=i;
}
return count;
}
}
线程池:
1.创建线程池
* 2.创建自定义线程的对象
* 3.将此对象作为参数传递到execute方法中(Runnable)或submit方法中(Callable)
* 4.关闭线程池shutdown();
public class Thread_Pool {
public static void main(String[] args) {
//创建容量为10的线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
MyPool myPool = new MyPool();
executorService.execute(myPool);
executorService.shutdown();
for (int i = 0; i <1000 ; i++) {
System.out.println("main...");
}
}
}
class MyPool implements Runnable{
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("pool...");
}
}
}