有三个线程ID分别是A、B、C,请用多线编程实现在屏幕上循环打印10次ABCABC......
方法一
使用多重同步块
代码如下:
package thread1;
public class Main_thread1 implements Runnable{
private String name;
private Object prev;
private Object self;
private Main_thread1(String name, Object prev, Object self) {
this.name = name;
this.prev = prev;
this.self = self;
}
public static void main(String[] args) throws Exception{
Object a = new Object();
Object b = new Object();
Object c = new Object();
Main_thread1 pa = new Main_thread1("A", c, a);
Main_thread1 pb = new Main_thread1("B", a, b);
Main_thread1 pc = new Main_thread1("C", b, c);
new Thread(pa).start();
Thread.sleep(100); //确保按顺序A、B、C执行
new Thread(pb).start();
Thread.sleep(100);
new Thread(pc).start();
Thread.sleep(100);
}
@Override
public void run() {
int count = 10;
while (count > 0) {
synchronized (prev) {
synchronized (self) {
System.out.print(name);
count--;
self.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
此处注意java.lang.Object中的两个方法:notify()和wait()。
notify():唤醒在此对象监视器上等待的单个线程。
wait():在其他线程调用此对象的notify()方法前,导致当前线程等待。
代码中
synchronized (prev) {
synchronized (self) {
System.out.print(name);
count--;
self.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
当线程pa运行时,运行至a.nofity()唤醒pb线程,且c.wait()使当前线程处于等待;当线程继续执行时,从断点处接着执行。即被唤醒后,从XXX.wait()下面的依据开始继续执行。
方法二
思路:使用同步块和标识。
代码如下:
package thread1;
public class Main_thread2 {
static boolean isThreadA = true;
static boolean isThreadB = false;
static boolean isThreadC = false;
public static void main(String[] args) throws Exception{
byte []print = new byte[0];
Thread t1 = new Thread(new Runnable(){
public void run(){
synchronized (print){
for(int i=0;i<10; i++){
while(!isThreadA){
try{
print.wait();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.print("A");
isThreadA = false;
isThreadB = true;
isThreadC = false;
print.notifyAll();
}
}
}
});
Thread t2 = new Thread(new Runnable(){
public void run(){
synchronized (print){
for(int i=0;i<10; i++){
while(!isThreadB){
try{
print.wait();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.print("B");
isThreadA = false;
isThreadB = false;
isThreadC = true;
print.notifyAll();
}
}
}
});
Thread t3 = new Thread(new Runnable(){
public void run(){
synchronized (print){
for(int i=0;i<10; i++){
while(!isThreadC){
try{
print.wait();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.print("C");
isThreadA = true;
isThreadB = false;
isThreadC = false;
print.notifyAll();
}
}
}
});
t1.start();
t2.start();
t3.start();
}
}