In cryptography, a key memorandum of understanding is a protocol in which two or more parties can agree on a key so that both influence the outcome. If this is done correctly, it prevents undesirable third parties from imposing an important decision on the appropriate parties. Protocols that are useful in practice also do not reveal to a listening party the key that has been agreed upon. The last option is to use a key tuning algorithm. Important agreement algorithms exchange certain public information between two parties so that they can calculate a common secret key. However, they do not exchange enough information as conversation listening companies can calculate the same freed key. In the JCE, these algorithms are represented by the KeyAgreement class (javax.crypto.KeyAgreement): this algorithm works according to the properties of the Diffie-Hellman pair of private keys/keys. These keys are not suitable for use in an encryption algorithm. they are only used in a most important agreement like this. The first public public key memorandum of understanding  that meets the above criteria was the Diffie-Hellman key exchange, in which two parties jointly exposed a generator to random numbers, so that an earpiece cannot easily determine what the resulting value is used to create a common key.
On the third question; To distribute public keys on the Internet, you need to build trust. You have to trust the other party. The key Diffie Hellman agreement alone does not create trust; just a common secret with another party. Therefore, you need a secure protocol (z.B TLS) with trust certificates or keys containing an authentication component. However, to establish such a protocol, a great deal of knowledge is needed; If you don`t fully understand the code you just showed us, you won`t be able to create such a protocol yourself. The exponential key exchange itself does not indicate prior agreement or subsequent authentication between participants. It has therefore been described as an anonymous key memorandum of understanding. In typical use, Bob and Alice would naturally run code in different classes, probably on different computers.
We`ve shown the code here with two threads in a shared object so you can run the example more easily (although you can expect: creating a Diffie-Hellman key is an expensive process, especially with a size of 1024; a size of 512 is better to test).