关于单循环打印99乘法表

下面是结果和源码

利用了线程的特性,以及使用数组越界的时候捕捉异常然后将线程停止

关于单循环打印99乘法表_第1张图片



public class Test {
	
	public static void main(String[] args) throws InterruptedException {
		int rowNum = 9;
		//初始化一个长度为N+1的数组这里为[0,0,0,0,0,0,0,0,0,0]
		int[] arr = new int[rowNum + 1]; 
		int i = 0;
		new Test99(rowNum, arr, i);
	}
}



public class Test99 {
	private int rowNum;
	private int[] arr;
	private int i;
	public Test99(int rowNum, int[] arr, int i) throws InterruptedException {
		this.rowNum = rowNum;
		this.arr= arr;
		this.i = i;
		try {
			arr[i+1] = arr[i] + 1;
			PrintThread printThread = new PrintThread(arr[++i], rowNum);
			printThread.start();
			//采用递归的方式
			//arr = [0,1,0,0,0,0,0,0,0,0]  i = 1;
			//arr = [0,1,2,0,0,0,0,0,0,0]  i = 2;
			//arr = [0,1,2,3,0,0,0,0,0,0]  i = 3;
			//arr = [0,1,2,3,4,0,0,0,0,0]  i = 4;
			//arr = [0,1,2,3,4,0,0,0,0,0]  i = 5;
			//arr = [0,1,2,3,4,5,0,0,0,0]  i = 6;
			//arr = [0,1,2,3,4,5,6,0,0,0]  i = 7;
			//arr = [0,1,2,3,4,5,6,7,0,0]  i = 8;
			//arr = [0,1,2,3,4,5,6,7,8,0]  i = 9;
			//arr = [0,1,2,3,4,5,6,7,8,9]  i = 10;
			new Test99(rowNum, arr, i);
		}
		//如果下标越界了,就捕捉异常,和停止线程  i = 10的时候下标越界
		catch (Exception e) {
			Thread.sleep((arr[--i] + 1) * 100);
			Thread.interrupted();
		}
	}
}

class PrintThread extends Thread {
	int length = 0;
	int rowNum = 0;
	public PrintThread (int length, int rowNum) { 
		this.length = length;
		this.rowNum =rowNum;
	}
	@Override
	public void run() {
		try {
			Thread.sleep(length * 100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
		for (int i = 1; i <= length; i++) {
			System.out.print(i * length + "\t");
		}
		System.out.println();
	}
}



你可能感兴趣的:(关于单循环打印99乘法表)