Getting started with threads

Threads are an embedded feature of Java, and threads are not easy to master. There are books devoted to Java threads, which readers can refer to. This shows the importance of Java threads. This article will introduce the basic knowledge of threads in detail.
  Sometimes you may want to write a program to perform related tasks at regular intervals. At this time, you can use Timer and TimerTask, which are very convenient. You can refer to here.

  There are two ways to implement a thread in Java, the first is to implement the Runnable interface to implement its run() method, and the second is to inherit the Thread class and override its run() method. Here is the code example:


  public class DoSomething implements Runnable {
  public void run(){
  // here is where you do something
  }
  }
  public class DoAnotherThing extends Thread {
  public void run(){
  // here is where you do something
  }
  }


  This The difference between the two methods is that if your class has inherited other classes, then you can only choose to implement the Runnable interface, because Java only allows single inheritance.

  A thread in Java has four states: running, ready, suspended, and terminated. If a thread ends, it means that he is a dead thread. When you call the start() method of a thread instance, the thread enters the ready state at this time. Note that it is not in the running state. When the virtual machine starts to allocate the running time slice of its CPU, the thread begins to enter the running state. Enter a waiting state, such as waiting for an event to occur, when the thread is in a suspended state.

  To start a thread, you only need to call the start() method. There are two ways to start a thread for the two methods of implementing a thread, as follows:


  DoSomething doIt = new DoSomething();
  Thread myThread = new Thread( doIt );
  myThread.start ();
  DoAnotherThing doIt = new DoAnotherThing();
  doIt.start();



The stop() method in Thread has been deprecated due to safety and other factors, so if you want to stop a thread, you can set a semaphore For example:
public class MyThread implements Runnable {
  private boolean quit = false;
  public void run(){
  while( !quit ){
  // do something
  }
  }

  public void quit(){
  quit = true;
  }
  }


  If each thread only does its own thing, then it is very simple, but sometimes several threads may access an object at the same time and may modify it, in this case you must use the thread's Synchronization uses the keyword synchronized in methods or code blocks, for example:


  public class Counter {
  private int counter;
  public synchronized int increment(){
  return ++counter;
  }

  public synchronized int decrement(){
  if( --counter < 0 ){
  counter = 0;
  }

  return counter;
  }
  }



  Each java object can be a monitor. When a thread accesses its synchronized method, it only allows only one thread to access it at a time, leaving other threads to wait in line . This prevents multithreading from causing damage to shared data. Remember that synchronized will consume system resources and reduce the efficiency of program execution, so it must be used when synchronization is required, especially in the development of J2ME.

If you want a thread to wait for an event to happen and then continue executing, then this involves thread scheduling. In java, it is implemented by wait(), notify(), notifyAll(). These three methods are defined in the Object class. When you want to suspend the thread, call the obj.wait() method. In the same Calling notify() on obj restarts the thread. Finally, this article ends with the example of Producer/Consumer provided by SUN. The content is that the Producer generates a number and the Consumer consumes this number. This small program basically covers all the knowledge points in this article. Please study the code in detail


  public class Producer extends Thread {
  private CubbyHole cubbyhole;
  private int number;
  public Producer(CubbyHole c, int number) {
  cubbyhole = c;
  this.number = number;
  }

  public void run() {
  for (int i = 0; i < 10; i++) {
  cubbyhole.put(i);
  System.out.println("Producer #" + this.number
  + " put: " + i);
  try {
  sleep((int)(Math. random() * 100));
  } catch (InterruptedException e) { }
  }
  }
  }


  public class CubbyHole {
  private int contents;
  private boolean available = false;


  public synchronized int get() {
  while (available == false) {
  try {
  wait();
  } catch (InterruptedException e) { }
  }
  available = false;
  notifyAll();
  return contents;
  }

  public synchronized void put(int value) {
  while (available == true) {
  try {
  wait();
  } catch (InterruptedException e) { }
  }
  contents = value;
  available = true;
  notifyAll();
  }
  }

  public class Consumer extends Thread {
  private CubbyHole cubbyhole;
  private int number;

  public Consumer(CubbyHole c, int number) {
  cubbyhole = c;
  this.number = number;
  }
   public void run() {
  int value = 0;
  for (int i = 0; i < 10; i++) {
  value = cubbyhole.get();
  System.out.println("Consumer #" + this.number
  + " got: " + value);
  }
  }
  }
  public class ProducerConsumerTest {
  public static void main(String[] args) {
  CubbyHole c = new CubbyHole();
  Producer p1 = new Producer(c, 1);
  Consumer c1 = new Consumer(c, 1);

  p1.start();
  c1.start();
  }
  }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326531046&siteId=291194637