目录
一.lambda表达式(强烈推荐,最简单)
基础格式
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(()->{
//此处写线程实现的代码
}
});
thread.start();
//此处写主函数的代码
}
}
举例
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(()->{
int i = 0;
while(i<5){
System.out.println("阿米娅"+i);
i++;
}
});
thread.start();
int j = 10;
while(j>5){
System.out.println("爱莉希雅"+j);
j--;
}
}
}
运行结果
(线程和主程序运行结果可能会调换顺序)
二.继承 Thread, 重写 run
基础格式
class Mythread extends Thread{
@Override
public void run() {
//此处写你线程执行的代码
}
}
}
public class demo1 {
public static void main(String[] args) {
Mythread t1 = new Mythread();
t1.start();
//此处写你主函数的执行代码
}
}
举例
class Mythread extends Thread{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("八重神子"+i);
}
}
}
public class demo1 {
public static void main(String[] args) {
Mythread t1 = new Mythread();
t1.start();
for (int i = 10; i > 5; i--) {
System.out.println("豌豆射手"+i);
}
}
}
运行结果
(线程和主程序运行结果可能会调换顺序)
三.实现 Runnable, 重写 run
基础格式
class Mythread2 implements Runnable{
@Override
public void run() {
//此处写你多线程执行的代码
}
}
public class demo2 {
public static void main(String[] args) {
Mythread2 t1 = new Mythread2();
Thread t2= new Thread(t1);
t2.start();
//此处写你主线程执行的代码
}
}
举例
class Mythread2 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("海绵宝宝"+i);
}
}
}
public class demo2 {
public static void main(String[] args) {
Mythread2 t1 = new Mythread2();
Thread t2= new Thread(t1);
t2.start();
for (int i = 10; i >5 ; i--) {
System.out.println("派大星"+i);
}
}
}
运行结果
(线程和主程序运行结果可能会调换顺序)
四.使用匿名内部类,继承 Thread, 重写 run
基础格式
public class demo3 {
public static void main(String[] args) {
Thread t1 = new Thread(){
//此处写你多线程要执行的代码
};
t1.start();
//此处写你主线程执行的代码
}
}
举例
public class demo3 {
public static void main(String[] args) {
Thread t1 = new Thread(){
public void run(){
for (int i = 0; i < 5; i++) {
System.out.println("Tom"+i);
}
}
};
t1.start();
for (int i = 10; i > 5 ; i--) {
System.out.println("Jerry"+i);
}
}
}
运行结果
(线程和主程序运行结果可能会调换顺序)
五.使用匿名内部类,实现 Runnable, 重写 run
基础格式
其实就是在Thread里面多了一个new Runnable
public class demo4 {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
//此处写你线程执行的代码
});
t1.start();
//此处写你主函数执行的代码
}
}
举例
public class demo4 {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("盲僧"+i);
}
}
});
t1.start();
for (int i = 10; i > 5 ; i--) {
System.out.println("亚索"+i);
}
}
}
运行结果
(线程和主程序运行结果可能会调换顺序)