1.有A、B、C、D四个线程,A线程输出A, B线程输出B, C线程输出C,D线程输出D,要求, 同时启动四个线程, 按顺序输出ABCD;
本题主要通过join方法来实现顺序输出ABCD。
代码如下:
package thread;
/**
* @author Beauxie
*/
public class TestThread1 {
public static void main(String[] args) {
// 线程A
final Thread a = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("A");
}
});
// 线程B
final Thread b = new Thread(new Runnable() {
@Override
public void run() {
try {
// 执行b线程之前,加入a线程,让a线程执行
a.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B");
}
});
// 线程C
final Thread c = new Thread(new Runnable() {
@Override
public void run() {
try {
// 执行c线程之前,加入b线程,让b线程执行
b.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("C");
}
});
// 线程D
Thread d = new Thread(new Runnable() {
@Override
public void run() {
try {
// 执行d线程之前,加入c线程,让c线程执行
c.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("D");
}
});
// 启动四个线程
a.start();
b.start();
c.start();
d.start();
}
}
运行结果:
2.有A,B,C三个线程, A线程输出A, B线程输出B, C线程输出C 要求, 同时启动三个线程, 按顺序输出ABC, 循环10次;
代码如下:
package thread;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author Beauxie
*/
public class TestThresd2 {
// //通过JDK5中的锁来保证线程的访问的互斥
private static Lock lock = new ReentrantLock();
private static int state = 0;// 用state来判断轮到谁执行
private static final int RUN_NUMBER=100;//表示循环的次数
//A线程
static class ThreadA extends Thread {
@Override
public void run() {
for (int i = 0; i < RUN_NUMBER;) {
lock.lock();//获取锁定
if (state % 3 == 0) {
System.out.println("第"+(i+1)+"次:");
System.out.println("A");
state++;
i++;
}
lock.unlock();//释放锁定,不释放锁定,会被该线程一直保持
}
}
}
//B线程
static class ThreadB extends Thread {
@Override
public void run() {
for (int i = 0; i < RUN_NUMBER;) {
lock.lock();
if (state % 3 ==1) {
System.out.println("B");
state++;
i++;
}
lock.unlock();
}
}
}
//C线程
static class ThreadC extends Thread {
@Override
public void run() {
for (int i = 0; i < RUN_NUMBER;) {
lock.lock();
if (state % 3 == 2) {
System.out.println("C");
state++;
i++;
}
lock.unlock();
}
}
}
public static void main (String[] args){
new ThreadA().start();
new ThreadB().start();
new ThreadC().start();
}
}
在这里我将循环次数改成100次,运行结果:
本题参考自:http://love3400wind.blog.163.com/blog/static/796308012013117102941831/
如果各位有更好的思路,麻烦请告诉我,谢谢!