实现Id以区分将运行代码的多个客户端

时间:2016-05-31 17:09:37

标签: java

我正在实现一个应该模拟DataBase的代码。在这个过程中,我将同时运行相同代码的多个实例/客户端,并且需要一种方法来区分每次运行,因为每次实例运行时,它应该向PlaceHolder.txt文件添加一个新行,当user(instance)提交代码,它应该只将他的事务移动到DataBase.txt文件。 这是Transaction类:

public class Transaction{

private final String name;
private final int id;

public Transaction(){
    this.id = getId()+1;
    this.name= "T"+id;
}
public String getName(){
    return this.name;
}
public int getId(){
    return this.id;
}

public String toString(){
    return "Name: "+ name+"\nID: "+id+"\n";
}

调用它的函数就是这个:

private ArrayList<Transaction> transaction;
private static int id;
private static String name;

//Not Working
public synchronized String NewTransaction() {
    Transaction transaction;
    transaction= new Transaction ();
    transaction=transaction;
    System.out.print(transaction.toString() + "\n");
    return transaction.toString();
}

问题: 但编码不起作用。当我运行代码时,结果将始终为id = 1。我在代码中做错了什么?

4 个答案:

答案 0 :(得分:0)

int的默认值是0.因此,当你构造一个新的Transaction对象时,你会这样做.id = getId()+ 1;它总是1(0 + 1)。

您可以使用方法public static synchronized getNewId()和static int idToHandOut创建一个名为IdCreator.java的新类,并在那里跟踪发出的最后一个id,当有人要求新的id时,你把它增加1。

还有许多其他方法可以做到 - 你可以将时间戳作为id。

但基本上,你不能按照你写的方式指定id,因为它总是为1。

答案 1 :(得分:0)

根据一些建议实施解决方案:

class Junk {

    private class Transaction {
        private final String name;
        private final int id;

        public Transaction(int id){
            this.id = id;
            this.name= "T"+id;
        }

        public String getName(){
            return this.name;
        }

        public int getId(){
            return this.id;
        }

        public String toString(){
            return "Name: "+ name+"\nID: "+id+"\n";
        }
    }

    private ArrayList<Transaction> transactions;
    private int curr_id = 0;
    private String name;

    public synchronized String NewTransaction() {
        curr_id++;
        Transaction transaction = new Transaction(curr_id);
        return transaction.toString();
    }
}

答案 2 :(得分:0)

您可以通过一些修改来修复它:

if (bloggerDirs == null)
 MainUI.ShowDebug("bloggerDirs is null");
else
 MainUI.ShowDebug("bloggerDirs is NOT null");

现在你将得到不同的身份证明:

class Transaction{

    private static int ID;  // static var for unique identifier

    private final String name;
    public final int id;

    public Transaction(){
       ID++;
       this.id = ID
       this.name= "T" + ID;
    }

    public int getId(){
        return this.id;
    }
 ...
}

答案 3 :(得分:0)

你最好在这种情况下使用原子类型,虽然它可能会在极重负载下引入瓶颈,但是从中到高它应该没问题。

package transaction;

import java.util.concurrent.atomic.AtomicInteger;

public class Transaction {
    // static field to generate new numbers sequentially in thread-safe way
    private static final AtomicInteger idProvider = new AtomicInteger(0);

    private final int id;
    private final String name;

    public Transaction()
    {
        this.id = Transaction.idProvider.incrementAndGet();
        this.name = "T"+id;
    }

    public String getName(){
        return this.name;
    }

    public int getId(){
        return this.id;
    }

    public String toString(){
        return "Name: "+ name+"\nID: "+id;
    }
}

试验实例

package transaction;

public class Main {
    public static void main(String[] args)
    {
        System.out.println("Single threaded test");
        for(int i = 0; i < 3; i++)
        {
            Transaction t1 = new Transaction();
            Transaction t2 = new Transaction();
            System.out.println("t1: "+t1.toString());
            System.out.println("t2: "+t2.toString());
        }

        System.out.println("\nMulti-threaded test");
        for(int i = 0; i < 3; i++)
        {
            Thread w = new Thread()
            {
                public void run()
                {
                    try{ // simulate unpredictable execution via random delay in instance creation
                        Thread.currentThread().sleep((int)(Math.random()*10));
                    }
                    catch(InterruptedException ignore){}
                    Transaction t = new Transaction();
                    System.out.println(t);
                }
            };
            w.start();
        }

        try{ //Wait for all threads to finish
            Thread.currentThread().sleep(1000);
        }
        catch(InterruptedException ignore){}
        System.out.println("Done");
    }
}

结果:

Single threaded test
t1: Name: T1
ID: 1
t2: Name: T2
ID: 2
t1: Name: T3
ID: 3
t2: Name: T4
ID: 4
t1: Name: T5
ID: 5
t2: Name: T6
ID: 6

Multi-threaded test
Name: T7
ID: 7
Name: T8
ID: 8
Name: T9
ID: 9
Done

P.S。不知道你为什么要这样做

transaction=transaction;