Java多线程(三种实现方式)
Thread类
/**
* 继承Thread类,并重写run方法
* 通过start方法开启线程
*/
public class Test0913Thread {
public static void main(String[] args) {
MyThread1 myThread1 = new MyThread1();
myThread1.start();
MyThread2 myThread2 = new MyThread2();
myThread2.start();
}
}
class MyThread1 extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread1********************"+i);
try {
//休眠500毫秒
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyThread2 extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread2********************"+i);
try {
//休眠500毫秒
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
结果
Runnable接口
/**
* 继承Runnable接口,并实现run方法
* 和继承Thread类不同的是,Runnable接口没有start方法
* 可以通过new Thread( 继承了Runnable的对象 ).start()开启线程
*/
public class Test0913Runnable {
public static void main(String[] args) {
MyThread3 myThread3 = new MyThread3();
//将myThread3作为实例Thread类的参数
new Thread(myThread3).start();
MyThread4 myThread4 = new MyThread4();
new Thread(myThread4).start();
}
}
class MyThread3 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread1********************"+i);
try {
//休眠500毫秒
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyThread4 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread2********************"+i);
try {
//休眠500毫秒
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
结果
Callable接口
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* 继承Callable接口,并实现call方法
* 和Thread、Runnable不同的是,Callable是有返回值的
* Callable没有start方法,但也不能直接作为Thread对象的参数
* 可以作为FutureTask对象的参数进行一个封装,再由FutureTask对象作为Thread对象的参数
* 返回值通过FutureTask对象的get方法得到
*/
public class Test0913Callable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCall myCall =new MyCall();
FutureTask futureTask = new FutureTask(myCall);
new Thread(futureTask).start();
Object o = futureTask.get();
System.out.println(o);
}
}
class MyCall implements Callable{
@Override
public Object call() throws Exception {
int sum=0;
for (int i = 0; i < 10; i++) {
System.out.println("Thread运行中"+i);
sum+=i;
Thread.sleep(500);
}
return sum;
}
}
结果
Runnable接口的两种其他写法
public class Test0913Runnable2 {
public static void main(String[] args) {
//匿名内部类写法
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Runnable方法已执行");
}
};
new Thread(runnable).start();
//拉姆达表示法,如果只有一行代码可以把{}去掉
Runnable run=() ->{
System.out.println("Runnable方法已执行");
};
new Thread(run).start();
}
}