Topic: 请教多线程同步问题

  Print this page

1.请教多线程同步问题 Copy to clipboard
Posted by: ballfly
Posted on: 2006-03-08 00:33

import java.io.*;
public class fourThread implements Runnable
{
  public static void main(String args[])
  {
    fourThread th=new fourThread();
    Thread th1=new Thread(th);  
    Thread th2=new Thread(th);
    Thread th3=new Thread(th);
    Thread th4=new Thread(th);
    th1.start();
    th2.start();
    th3.start();
    th4.start();
    
    
  }
  
   int i=100;

  public void run()
  {
    
    
      for(;i>=50;i--)
      {
        System.out.println(Thread.currentThread().getName()+":"+i);
      }
    
      
      
      
      
  }
}

为何屏幕会打印出4个重复的93数字呢?
我的目的是:从100到50的不重复打印(用四个线程实现)
请问如何解决?

2.Re:请教多线程同步问题 [Re: ballfly] Copy to clipboard
Posted by: Skybus
Posted on: 2006-03-08 10:11

这个程序应该可以实现的,关键是对i的操作进行同步保护!

public class ThreadTest {
public static void main(String args[]) {
Threadnew th = new Threadnew();
new Thread(th).start();
new Thread(th).start();
new Thread(th).start();
new Thread(th).start();
}
}

class Threadnew implements Runnable {
int i = 100;

Object obj = new Object();

public void run() {

while (true) {
synchronized (obj) {//同步块
if (i >= 50) {
try {
Thread.sleep(10);
System.out.println(Thread.currentThread().getName()
+ ":" + i);
i--;

} catch (Exception e) {
e.printStackTrace();
}
}

}
if (i < 50)
break;
}

}
}


3.Re:请教多线程同步问题 [Re: ballfly] Copy to clipboard
Posted by: ballfly
Posted on: 2006-03-08 16:24

谢谢


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923