类一:
package test; public class Counter implements Runnable { private int number; public Counter(int number) { this.number = number; } @Override public void run() { for (int i = 0; i < 3; i++) { System.out.printf("%s: %d * %d = %d\n", Thread.currentThread().getName(), number, i, i * number); } } }测试类:
package test; public class TestCounter { public static void main(String[] args) { for (int i = 0; i < 3; i++) { Counter calculator = new Counter(i); Thread thread = new Thread(calculator); thread.start(); } } }
测试结果:
Thread-0: 0 * 0 = 0 Thread-1: 1 * 0 = 0 Thread-1: 1 * 1 = 1 Thread-1: 1 * 2 = 2 Thread-2: 2 * 0 = 0 Thread-0: 0 * 1 = 0 Thread-2: 2 * 1 = 2 Thread-2: 2 * 2 = 4 Thread-0: 0 * 2 = 0