Java并发编程:线程的创建和执行

来源:互联网 发布:西安爱知中学学费 编辑:程序博客网 时间:2024/06/05 08:44

类一:

package test;public class Counter implements Runnable {private int number;public Counter(int number) {this.number = number;}@Overridepublic 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