Problem Description
利用多线程按要求打印数字,线程计数从100开始,Thread1先打印101,102,103,104,105,106,107,108,然后是Thread2打印109,110,111,112,113,114,115,116,然后是Thread3打印117,118,119,120,121,122,123,124,接着再由Thread1打印125,126,127,128,129,130,131,132….以此类推, 直到打印到204。
请将前半部分代码补充完整。
// 你的代码将嵌入这里
public class Main {
public static void main(String[] args) throws InterruptedException {
object o = new object(); // 注意,O这里应该是大写,是Java祖先对象object,因为系统原因改不过来
new Thread(new PrintRunnable(1,o)).start();
new Thread(new PrintRunnable(2,o)).start();
new Thread(new PrintRunnable(3,o)).start();
}
}
Output Description
Thread1:101
Thread1:102
Thread1:103
Thread1:104
Thread1:105
Thread1:106
Thread1:107
Thread1:108
Thread2:109
Thread2:110
Thread2:111
Thread2:112
Thread2:113
…(此处省去中间打印的内容)
Thread1:200
Thread1:201
Thread1:202
Thread1:203
Thread1:204
题解代码
class PrintRunnable implements Runnable{
static Object obj = new Object();
int name;//进程的id
static int now = 1;//当前执行的进程
static int num = 101;//设置为静态常量 多个线程共用
public PrintRunnable(int name,Object o)
{
this.name=name;
obj = o;
}
@Override
public void run()
{
while(true)
{
synchronized(obj){
if(now == name)//如果当前进程的名字匹配
{
if(num > 204)
{
break;
}
for(int i = 0 ; i< 8; i++)
{
System.out.println("Thread"+name+":"+num);
num++;
}
now = (now + 1) % 4;
if(now == 0)
{
now++;
}
}
else//如果不匹配
{
obj.notifyAll();//唤醒其他的所有进程
if(num > 204)
{
break;
}
else {
try {
obj.wait();//并且让此进程进行等待
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
}
// 你的代码将嵌入这里
public class Main {
public static void main(String[] args) throws InterruptedException {
Object o = new Object(); // 注意,O这里应该是大写,是Java祖先对象object,因为系统原因改不过来
new Thread(new PrintRunnable(1,o)).start();
new Thread(new PrintRunnable(2,o)).start();
new Thread(new PrintRunnable(3,o)).start();
}
}