sleep method Java threads

  sleep method signature:

  public static void sleep (long millis)

  sleep method is a method of the Thread class, the role is: executing thread to sleep within the specified milliseconds (suspended)

  Parameter sleep time, in milliseconds

  package Threadproj;

  class MyThread implements Runnable{

  int i;

  public void run() {

  for(i = 1 ; i <= 10 ; i++) {

  System.out.println (. Thread.currentThread () getName () + "is running on" + i + "times");

  try {

  Thread.sleep(100);

  } catch (InterruptedException e) {

  // TODO Auto-generated catch block

  e.printStackTrace ();

  }

  }

  public class SleepDemo {

  public static void main(String[] args)

  {MyThread m = new MyThread();

  Thread mt = new Thread(m);

  mt.start();}

  }

  You can control thread refresh time

  Thread sleep time and sleep are also not related to the oh ~

  package Threadproj;

  class MyThread implements Runnable{

  public void run() {

  for(int i = 1 ; i <= 10 ; i++) {

  System.out.println (. Thread.currentThread () getName () + "is running on" + i + "times");

  try { Wuxi good ××× hospital http://www.zzchnk.com/

  Thread.sleep(100);

  } catch (InterruptedException e) {

  // TODO Auto-generated catch block

  e.printStackTrace ();

  }

  }

  public class SleepDemo {

  public static void main(String[] args) {

  MyThread m = new MyThread();

  Thread mt = new Thread(m);

  mt.start();

  Thread mt1 = new Thread(m);

  mt1.start();

  }

  }

  Two threads such a result is significant because the probability of another thread get the CPU in sleep, hence the situation is more regular alternately executed.


Guess you like

Origin blog.51cto.com/14335413/2404240