方法一:继承Thread类创建线程
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i<= 20; i++) {
if(i%2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
public static void main(String[] args) {
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
myThread1.setName("线程1");
myThread2.setName("线程2");
myThread1.start();
myThread2.start();
}
}
方法二:实现Runnable接口创建线程
public class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i<= 20; i++) {
if(i%2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
public static void main(String[] args) {
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
Thread thread1 = new Thread(myThread1);
Thread thread2 = new Thread(myThread2);
thread1.setName("线程1");
thread2.setName("线程2");
thread1.start();
thread2.start();
}
方法三:实现Callable接口创建线程
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class NumThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i<= 20; i++) {
if(i%2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
sum += i;
}
}
return sum;
}
}
public class MyThread {
public static void main(String[] args) {
NumThread numThread = new NumThread();
FutureTask<Integer> futureTask = new FutureTask(numThread);
new Thread(futureTask).start();
try {
Integer sum = futureTask.get();
System.out.println("整数和为:" + sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
方法四:使用线程池创建线程
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class NumThread implements Runnable{
@Override
public void run() {
for (int i = 0; i<= 20; i++) {
if(i%2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class MyThread {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
for (int i = 0; i<10; i++){
service.execute(new NumThread());
}
service.shutdown();
}
}