//定义类实现Runnable接口
class Test2 implements Runnable {
Object obj = new Object();
private int piao = 1000;
public void run() {
synchronized(obj) { //加上了同步
while(true) {
if(piao > 0) {
try {Thread.sleep(10);} catch(InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + "run..." + piao--);
}
}
}
}
}
class ThreadTest2 {
public static void main(String[] args) {
//创建Runnable接口的子类对象
Test2 t = new Test2();
//创建四个线程,把Runnable接口的子类对象当成实参传递给线程的构造函数
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
//开启四个线程
t1.start();
t2.start();
t3.start();
t4.start();
}
} |
|