黑马程序员技术交流社区
标题:
此线程加上同步后每次都只执行一个线程,求大神帮忙
[打印本页]
作者:
追逐
时间:
2014-3-18 10:43
标题:
此线程加上同步后每次都只执行一个线程,求大神帮忙
//定义类实现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();
}
}
作者:
muma
时间:
2014-4-4 10:04
把同步加在while循环内
class Test2 implements Runnable {
Object obj = new Object();
private int piao = 100;
public void run() {
while(true) {
synchronized(obj)/*将同步加到while循环内部*/ {
if(piao > 0) {
try {Thread.sleep(10);} catch(InterruptedException e) {}
System.out.println("show 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();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2