第一种方式:继承Thread
package com.chang;
public class ThreadDemo1 {
public static void main(String[] args) {
/*
多线程第一种启动方式:
1.定义一个类继承Thread
2.重写run方法
3.创建子类对象,启动线程
*/
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
//给线程取个名
myThread1.setName("线程一");
myThread2.setName("线程二");
//开启线程
myThread1.start();
myThread2.start();
}
}
package com.chang;
public class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(this.getName()+"Hello world!");
}
}
}
第二种方式:实现Runnable
package com.chang.bao2;
import com.chang.bao1.MyThread;
public class ThreadDemo2 {
public static void main(String[] args) {
/*
多线程的第二种实现方式:
1.定义一个类实现Runnable
2.重写里面的run方法
3.创建类对象
4.创建线程(Thread),开启线程
*/
//表示多线程要执行的任务
MyRun myRun = new MyRun();
//创建线程,把任务丢给线程
Thread thread1= new Thread(myRun);
Thread thread2= new Thread(myRun);
//给线程起名
thread1.setName("线程1");
thread2.setName("线程2");
//开线程
thread1.start();
thread2.start();
}
}
package com.chang.bao2;
public class MyRun implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
//获取当前线程对象
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"Hello,world");
}
}
}
第三种方式:利用Callable接口和Future接口实现
package com.chang.bao3;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
/*
多线程实现的第三种方式:
特点:可以拿到多线程运行的结果
1.创建一个MyCallable类,实现Callable接口
2.重写call方法(有返回值,表示多线程运行的结果)
3.创建MyCallable的对象(表示多线程要执行的任务)
4.创建FutureTask的对象(管理多线程运行结果)
5.创建线程对象,启动线程
*/
//表示线程要执行的任务
MyCallable myCallable = new MyCallable();
//管理线程运行结果
FutureTask<Integer> integerFutureTask = new FutureTask<Integer>(myCallable);
Thread thread = new Thread(integerFutureTask);
thread.start();
Integer result = integerFutureTask.get();
System.out.println("多线程运行结果:"+result);
}
}
package com.chang.bao3;
import java.util.concurrent.Callable;
public class MyCallable implements Callable<Integer> {
//返回1-100之间的和
@Override
public Integer call() throws Exception {
int sum=0;
for (int i = 1; i <=100; i++) {
sum=sum+i;
}
return sum;
}
}