1.继承Thread类
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"=============="+i);
}
}
public static void main(String[] args) {
// 创建线程对象
MyThread myThread = new MyThread();
// 启动线程
myThread.run();
myThread.start();
// 主线程执行
// for (int i = 0; i < 100; i++) {
// System.out.println(Thread.currentThread().getName()+"=============="+i);
// }
}
}
2.实现Runnable接口
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+"-------->"+i);
}
}
public static void main(String[] args) {
// 创建thread对象,runnable对象
Thread thread = new Thread(new MyRunnable());
// 调用start方法
thread.start();
// 匿名内部类
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "-------->" + i);
}
}
});
thread1.start();
// lambda表达式
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "-------->" + i);
}
});
thread2.start();
}
}
3.实现Callable接口
public class MyCallable implements Callable<Long> {
@Override
public Long call() throws Exception {
long sum = 0;
for (int i = 0; i < 1000000000; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) {
FutureTask<Long> futureTask = new FutureTask<>(new MyCallable());
Thread thread = new Thread(futureTask);
thread.start();
try {
Long aLong = futureTask.get();
System.out.println(aLong);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
相关问题:
1.执行run和start的区别:调用run方法是在主线程中同步执行的,调用start方法后才会启动新的线程去执行
2.继承Thread类和实现Runnable接口的区别:
1>java是单继承的,继承Thread类就不能继承其他类,实现Runnable接口没有此限制
2>继承Thread类不强制重写run方法,实现Runnable接口强制重写,减少出错
3>Runnable可以使用lambda表达式,语法简洁