网易一面编程题
三个线程ABC,要求打印出A->B->C
方法一
public class ThreadMain {
public static void printA() {
System.out.print("A->");
}
public static void printB() {
System.out.print("B->");
}
public static void printC() {
System.out.print("C");
}
public static void main(String[] args) {
new Thread(new ThreadA()).start();
}
}
class ThreadA implements Runnable {
@Override
public void run() {
new Thread(new ThreadB()).start();
ThreadMain.printA();
}
}
class ThreadB implements Runnable {
@Override
public void run() {
new Thread(new ThreadC()).start();
ThreadMain.printB();
}
}
class ThreadC implements Runnable {
@Override
public void run() {
ThreadMain.printC();
}
}
方法二
**
* join方法把指定的线程添加到当前线程中,可以不给参数直接thread.join(),
* 也可以给一个时间参数,单位为毫秒thread.join(500)。事实上join方法是通过wait方法来实现的。
* 比如线程A中加入了线程B.join方法,则线程A默认执行wait方法,释放资源进入等待状态,此时线程B获得资源,
* 执行结束后释放资源,线程A重新获取自CPU,继续执行。由此实现线程的顺序执行。
*/
public class TestJoin {
public static void main(String[] args) throws InterruptedException {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
Thread3 t3 = new Thread3();
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
}
}
class Thread1 extends Thread{
public void run(){
System.out.print("A->");
}
}
class Thread2 extends Thread{
public void run(){
System.out.print("B->");
}
}
class Thread3 extends Thread{
public void run(){
System.out.print("C");
}
}