Head First JavaChapter 15

Make a Connection

Tharaka Dissanayake
3 min readJul 19, 2022

Socket connection.

A socket connection is an object that is used to connect computers. Its constructor accepts IP address and port number as parameters.

Creating a socket

Writing data to a Socket

Multithreading in Java

Multithreading is creating multiple threads. They are running at once. A thread is a separate call stack. Every java application starts up the main thread. JVM has responsible for starting the main thread.

How to launch a new thread:

BULLET POINTS

  • A thread with a lower-case ‘t’ is a separate thread of execution in Java.
  • Every thread in Java has its own call stack.
  • A Thread with a capital ‘T’ is the java. lang.Thread class. A Thread object represents a thread of execution.
  • A Thread needs a job to do. A Thread’s job is an instance of something that implements the Runnable interface.
  • 􀂃 The Runnable interface has just a single method, run().
  • This is the method that goes on the bottom of the new call stack. In other words, it is the first method to run in the new thread.
  • 􀂃 To launch a new thread, you need a Runnable to pass to the Thread’s constructor.
  • A thread is in the NEW state when you have instantiated a Thread object but have not yet called start().
  • When you start a thread (by calling the Thread object’s start() method), a new stack is created, with the Runnable’s run() method on the bottom of the stack.
  • The thread is now in the RUNNABLE state, waiting to be chosen to run.
  • 􀂃 A thread is said to be RUNNING when the JVM’s thread scheduler has selected it to be the currently running thread. On a single-processor machine, there can be only one currently-running thread.
  • Sometimes a thread can be moved from the RUNNING state to a BLOCKED (temporarily non-runnable) state.
  • A thread might be blocked because it’s waiting for data from a stream, because it has gone to sleep, or because it is waiting for an object’s lock.
  • Thread scheduling is not guaranteed to work in any particular way, so you cannot be certain that threads will take turns nicely.
  • You can help influence turn-taking by putting your threads to sleep periodically.

--

--