我正在努力实现这个: First Thread打印1,Second Thread打印2,Third Thread打印3,First Thread打印4,依此类推:
我做了这个并且正在努力:
class Display implements Runnable
{
int threadId;
static int v=1;
static int turn=1;//init
static Object monitor=new Object();
Display(int id)
{
this.threadId=id;
}
public void run() {// TODO Auto-generated method stub
print();
}
private void print() {
// TODO Auto-generated method stub
while(v<100)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
synchronized(monitor)
{
if(threadId==1)
{
if(turn!=1)
{
try {
monitor.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
System.out.println(threadId + ":"+v);
v++;
turn=2;
monitor.notifyAll();
}
}
else if(threadId==2)
{
if(turn!=2)
{
try {
monitor.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
System.out.println(threadId+":"+v);
v++;
turn=3;
monitor.notifyAll();
}
}
else
{
if(turn!=3)
{
try {
monitor.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
System.out.println(threadId+":"+v);
v++;
turn=1;
monitor.notifyAll();
}
}
}
}
}
}
public class Print {
public static void main(String[] ar)
{
Thread t1= new Thread(new Display(1));
Thread t2= new Thread(new Display(2));
Thread t3= new Thread(new Display(3));
t1.start();
t2.start();
t3.start();
}
}
输出是这样的:
1:1
2:2
3:3
1:4
2:5
它达到了目的但是如果我还有两个可以交替打印的线程,那么我必须使用更多的If条件。
任何人都可以建议以更好的形式编写此代码,以更干净的方式完成该任务,以便在添加更多线程时可以扩展。
答案 0 :(得分:0)
您需要为线程提供最高ID。在此之后,您可以使用模运算符简化代码。
class Display implements Runnable {
int threadId;
static int v = 1;
static int higehstId = 0;
static Object monitor = new Object();
Display(int id) {
this.threadId = id;
}
public void run() {
print();
}
private void print() {
while (v < 100) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synchronized (monitor) {
if ((v - 1) % higehstId == threadId - 1) {
System.out.println(threadId + ":" + v);
v++;
monitor.notifyAll();
} else {
try {
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] ar) {
Thread t1 = new Thread(new Display(1));
Thread t2 = new Thread(new Display(2));
Thread t3 = new Thread(new Display(3));
Thread t4 = new Thread(new Display(4));
Thread t5 = new Thread(new Display(5));
Display.higehstId = 5;
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
如果将v初始化为0并开始从0开始编号,则可以将if语句简化为:
if(v % highestId == threadId)