黑马程序员技术交流社区
标题:
线程同步??
[打印本页]
作者:
TS__likewise
时间:
2014-6-18 21:42
标题:
线程同步??
class ThreadDemo {
public static void main(String[] args)
{ TestThread t = new TestThread();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class TestThread implements Runnable {
int tickets = 100;
public void run() {
String str = "";
while(true)
{
synchronized(str)
{
if(tickets<=0)
break;
System.out.println(Thread.currentThread().getName()
+ " is saling " + tickets--);
}
}
}
}
这么做不对吗,为什么不能实现各自的同步
作者:
keep_moving
时间:
2014-6-19 11:38
楼主,刚刚测试了一下你的程序,没得问题,你可能觉得同步不明显,你可以把 int tickets = 100;改成 int tickets = 10000,; 这时你可以看到4个线程都能执行到,因为cpu多个线程上快速切换执行,数值小了效果不明显
作者:
TS__likewise
时间:
2014-6-19 22:14
keep_moving 发表于 2014-6-19 11:38
楼主,刚刚测试了一下你的程序,没得问题,你可能觉得同步不明显,你可以把 int tickets = 100;改成 int t ...
程序可以运行,同步不对,不是不明显
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2