我在22号的笔记中不是有一个疑问吗?为什么我编的程序没有不同步的现象产生呢,我把它发到csdn上去了,现在我已经基本解决这个问题了,下面是论坛的回复纪录摘要
回复人:bluesmile979(笑着) ( ) 信誉:100 2003-01-22 21:08:00 得分:0
说说我的看法,我认为最大的问题在于多线程,看了你的代码,好像只有两个线成了。而例子中应该是比较多的线程,多个线程竞争时间片,被打断的几率自然就大得多了。就算你加了循环,由于机器的运算速度,仍然没有多个线程竞争那么现象明显。不知道各位以为如何。
回复人:xm4014(forrest) ( ) 信誉:100 2003-01-22 22:07:00 得分:0
to bluesmile979(笑着)
我也曾经想到过是否因为线程太少而导致,但是我将think in java的例程中的两个参数都设为1来运行,那么最后也就和我写的程序一样,只有两个线程,结果照样有不同步.这又怎么解释呢
回复人:tianfeichen(侧耳倾听) ( ) 信誉:110 2003-01-22 23:57:00 得分:0
线程的安排毕竟是随机的,很少会有不同步的出现,次数少了不容易发现。
我常用的方法是,先让无限循环开始,循环的时候也不要求输出什么的,只加上一个停止的条件,比如:
if (counter1 != counter2)剩下的就是等了,一般十几秒甚至几秒就出结果了,可以发现记数已经到几十万或者几百万了。
{
system.out.println(counter1 + " ," + counter2)
system.exit(0);
}
class twocounter extends thread {
private int count1 = 0, count2 = 0;
private boolean started=false;
public void start(){
if (!started)
{
started=true;
super.start();
}
}
public void run() {
while (true) {
count1++;
count2++;
// system.out.println("count1="+count1+",count2="+count2);
try {
sleep(500);
} catch (interruptedexception e){system.out.println("twocounter.run");}
}
}
public void synchtest() {
// sharing2.incrementaccess();
if(count1 != count2)
{system.out.println(count1+","+count2);
system.exit(0);
}
}
}
class watcher extends thread {
private sharing2 p;
public watcher(sharing2 p) {
this.p = p;
start();
}
public void run() {
while(true) {
p.s.synchtest();
try {
sleep(500);
} catch (interruptedexception e){system.out.println("watcher.run");}
}
}
}
public class sharing2 {
twocounter s;
private static int accesscount = 0;
public static void incrementaccess() {
// accesscount++;
// system.out.println("accesscount="+accesscount);
}
public static void main(string[] args) {
sharing2 aaa = new sharing2();
aaa.s=new twocounter();
aaa.s.start();
new watcher(aaa);
}
} ///:~class threada
{
public static void main(string[] args)
{
threadb b=new threadb();
b.start();
system.out.println("b is start....");
synchronized(b)//括号里的b是什么意思,起什么作用?
{
try
{
system.out.println("waiting for b to complete...");
b.wait();//这一句是什么意思,究竟让谁wait?
system.out.println("completed.now back to main thread");
}catch (interruptedexception e){}
}
system.out.println("total is :"+b.total);
}
}
class threadb extends thread
{
int total;
public void run()
{
synchronized(this)
{
system.out.println("threadb is running..");
for (int i=0;i<100;i++ )
{
total +=i;
system.out.println("total is "+total);
}
notify();
}
}
}
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器