如何序列化myCount变量?

时间:2016-05-01 18:12:05

标签: java thread-safety

如何序列化myCount变量,每个线程以独占模式递增?后来的下一个线程会根据myCount的新值增加它吗?所以myCount将逐个被线程逐个增加?

目前我的结果如下:

    starting main thread----
    -----this is Main1
    ex Thread:2
    ex Thread:3
    -----this is Main3
    ex Thread:4
    -----this is Main4
    ex Thread:5
    -----this is Main5
    -----this is Main6
    ex Thread:7
    -----this is Main8
    ex Thread:9
    -----this is Main10
    ex Thread:11

--------------- code -------------------

    class MySamThread extends Thread {
    public static int myCount=0;
    public void run() {
    while(MySamThread.myCount<=10){
        try{System.out.println("ex Thread:"+(++MySamThread.myCount));
            Thread.sleep(100);          
        }catch (InterruptedException iex){
        System.out. println("exception in thread:"+iex.getMessage());}
        }}}


    public class RunSamThread {
    public static void main (String a[]){
    System.out.println("starting main thread----");
    MySamThread mst=new MySamThread();
    mst.start();
    while(MySamThread.myCount<=10){
      try{
          System.out.println("-----this is Main"+  
    (++MySamThread.myCount));
          Thread.sleep(100);
      } catch (InterruptedException iex){``
          System.out.println("exception in main   
   thread"+iex.getMessage());}    
    }}}

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

我想你问的是如何同步而不是序列化?

你可以在MySamThread中添加一个方法,如下所示 public static synchronized int incrementCount() { return ++mycount; }
而不是从主线程和线程中调用++MySamThread.myCount,而是呼叫MySamThread.incrementCount()
这将确保一次只有一个线程递增计数。