重写run方法,使用start()开启线程,如此,就可以同时做多件事情
public class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread()+ " " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread()+ " " + i);
}
}
}
因为java是单继承机制,所以实现接口的方式更常使用。同样需要重写run方法,使用start()开启线程
public class MyThread2 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread()+ " " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread2 mt = new MyThread2();
Thread t = new Thread(mt);
t.start();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread()+ " " + i);
}
}
}
通过此种方式开启的线程,可以存在返回值,主线程可以等待此线程执行完毕之后继续执行,也可以选择兵分两路
重写call()方法
public class MyThread3 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 100; i++) {
sum+=i;
}
return sum;
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Callable<Integer> callable = new MyThread3();
FutureTask<Integer> task = new FutureTask<>(callable);
new Thread(task).start();
Integer integer = task.get();
System.out.println(integer);//输出4590
}
}
原文:https://www.cnblogs.com/zhiyuanqiyuan/p/14772834.html