1.使用线程的join方法
public static void main(String[] args) {
final Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("起床");
}
});
final Thread t2 = new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
t1.join();
System.out.println("洗脸");
}
});
final Thread t3 = new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
t2.join();
System.out.println("吃饭");
}
});
t3.start();
t2.start();
t1.start();
}
2.使用主线程的join方法
public static void main(String[] args) throws InterruptedException {
final Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("起床");
}
});
final Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("洗脸");
}
});
final Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("吃饭");
}
});
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
}
3.使用线程的wait方法(实现生产者消费者)
public class ThreadA extends Thread {
private MyServer server;
public ThreadA(MyServer server) {
this.server = server;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
server.print1();
}
}
}
public class ThreadB extends Thread {
private MyServer server;
public ThreadB(MyServer server) {
this.server = server;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
server.print2();
}
}
}
public class ThreadC extends Thread {
private MyServer server;
public ThreadC(MyServer server) {
this.server = server;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
server.print3();
}
}
}
public class MyServer {
private volatile int flag = 1;
public synchronized void print1() {
while (flag != 1) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程1");
flag = 2;
this.notifyAll();
}
public synchronized void print2() {
while (flag != 2) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程2");
flag = 3;
this.notifyAll();
}
public synchronized void print3() {
while (flag != 3) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程3");
flag = 1;
this.notifyAll();
}
}
public class Main1 {
public static void main(String[] args) throws InterruptedException {
MyServer server=new MyServer();
ThreadA a=new ThreadA(server);
ThreadB b=new ThreadB(server);
ThreadC c=new ThreadC(server);
b.start();
c.start(); a.start();
}
}
简单的就是这三种,还有其他的方式后续再添加