日期:2014-05-18 浏览次数:20705 次
public class MutiThread extends Thread {
private byte[] lock = new byte[0];
private int i;
private MutiThread(int i) {
this.i = i;
}
public void run() {
synchronized (lock) {
if (i == 1)
System.out.println("A");
if (i == 2)
System.out.println("B");
if (i == 3)
System.out.println("C");
}
}
public static void main(String[] args) {
MutiThread mutiThread1 = new MutiThread(1);
mutiThread1.start();
MutiThread mutiThread2 = new MutiThread(2);
mutiThread2.start();
MutiThread mutiThread3 = new MutiThread(3);
mutiThread3.start();
}
}
class Printer implements Runnable{
private static Object lock=new Object();
private static int current=0;
private String content=null;
private int flag=0;
public Printer(String content,int flag){
this.content=content;
this.flag=flag;
}
public void run{
int times=0;
while(times<19){
synchronized (lock) {
while(current%3!=flag){
try{
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(content);
times++;
Runnable.current++;
lock.notifyAll();
}
}
}
}
public class ThreadTest
{
public static void main(String[] args)
{
new Thread(new Printer("A",0)).start();
new Thread(new Printer("B",1)).start();
new Thread(new Printer("C",2)).start();
}
}