62,615
社区成员
发帖
与我相关
我的任务
分享
package my_tesyt;
class NumberCla{
private String threadName;
int index = 0;;
int[] num=new int[75];
int rows=0;
public NumberCla(int[] num){
this.num=num;
}
public void print1(){
synchronized (this) {
int mynum=(index+4);
int last=num[mynum];
int threadnum=(((last/5)%3)==0?3:(last/5)%3);
while(threadnum!=1){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
int temp=index;
if(index<74){
for(int i=index;i<num.length;i++){
System.out.println(num[i]);
rows++;
System.out.println("打印行数:"+rows);
index++;
if(index-temp==5){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public void print2(){
synchronized (this) {
int mynum=(index+4);
int last=num[mynum];
int threadnum=(((last/5)%3)==0?3:(last/5)%3);
while(threadnum!=2){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
int temp=index;
if(index<74){
for(int i=index;i<num.length;i++){
System.out.println(num[i]);
rows++;
System.out.println("打印行数:"+rows);
index++;
if(index-temp==5){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public void print3(){
synchronized (this) {
int mynum=(index+4);
int last=num[mynum];
int threadnum=(((last/5)%3)==0?3:(last/5)%3);
while(threadnum!=3){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
int temp=index;
if(index<74){
for(int i=index;i<num.length;i++){
System.out.println(num[i]);
rows++;
System.out.println("打印行数:"+rows);
index++;
if(index-temp==5){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
class myThred1 extends Thread{
private NumberCla sync;
public myThred1(NumberCla sync){
this.sync=sync;
}
@Override
public void run() {
sync.print1();
}
}
class myThred2 extends Thread{
private NumberCla sync;
public myThred2(NumberCla sync){
this.sync=sync;
}
@Override
public void run() {
sync.print2();
}
}
class myThred3 extends Thread{
private NumberCla sync;
public myThred3(NumberCla sync){
this.sync=sync;
}
@Override
public void run() {
sync.print3();
}
}
public class Hellon{
public static void main(String[] args) {
int[] nums = new int[75];
for(int i=0;i<75;i++){
nums[i]=i+1;
}
NumberCla sync = new NumberCla(nums);
Thread t1=new myThred1(sync);
t1.setName("t1");
Thread t2=new myThred2(sync);
t2.setName("t2");
Thread t3=new myThred3(sync);
t3.setName("t3");
t1.start();
t2.start();
t3.start();
}
}