多线程

例一:最基本的一个多线程例子

package 多线程;
public class 多线程first {
 public static void main(String[] args){
  Thread t1 = new Thread(new MyThread());

//  Thread t1 = new Thread(new MyThread(),"小白线程");
  t1.start();  
 } 
 
}
 class MyThread implements Runnable{
  @Override
  public void run() {
   System.out.println("获取当前线程的名称:"+Thread.currentThread().getName()); 
   }  
 }

例二: 

package 多线程;
public class 多线程second {
 /**
  * sleep方法的原理:
  * 让当前线程进入休眠状态,让出当次执行的CPU时间,但是该线程不丢失任何监视器的所属权。
  *
  */
 public static void main(String[] args) {
   MyThread2 my = new MyThread2();
   Thread t1 = new Thread(my);
   Thread t2 = new Thread(my);
   t1.start();
   t2.start();   
  }
 }

 class MyThread2 implements Runnable{
  @Override
  public void run() {
   for (int i = 0; i < 10; i++) {
    System.out.println(Thread.currentThread().getName()+"-"+i);
    try {
     //让当前线程进入休眠状态
     Thread.sleep(1000);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }
 }

----------

来不及缓冲1秒,就就行了下一个开启线程。

start是开启线程,run是线程里面的一个方法。

例三:

package 多线程;
public class 多线程second {
 /**
  * sleep方法的原理:
  * 让当前线程进入休眠状态,让出当次执行的CPU时间,但是该线程不丢失任何监视器的所属权。
  *
  */
 public static void main(String[] args) {
   MyThread2 my = new MyThread2();
   Thread t1 = new Thread(my);
   Thread t2 = new Thread(my);
   t1.start();
   t2.start(); 
//当前main线程。反映竟然是第一个出来。不对,另外一个则是后面。所以是随机的时间
   System.out.println(Thread.currentThread().getName()+"-");
 
   
  }
 }

 class MyThread2 implements Runnable{
  @Override
  public void run() {
   for (int i = 0; i < 10; i++) {
    System.out.println(Thread.currentThread().getName()+"-"+i);
    try {
     //让当前线程进入休眠状态
     Thread.sleep(1000);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }
 }

例四:阻塞状态,等待当前线程执行终止,或指定的等待时间(毫秒,纳秒)

package com.vince.thread;

/**
 * join方法:等待当前线程执行终止,或指定的等待时间(毫秒,纳秒)
 * @author lamp
 *
 */
public class ThreadDemo3 {

 public static void main(String[] args) {
  MyThread3 my = new MyThread3();
  Thread t1 = new Thread(my);
  t1.start();
  
  for (int i = 0; i < 10; i++) {
   System.out.println("main-"+i);
   if(i==5){
    try {
     t1.join();//等待该线程终止。
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  
 }

}
class MyThread3 implements Runnable{
 @Override
 public void run() {
  for (int i = 0; i < 10; i++) {
   System.out.println(Thread.currentThread().getName()+"-"+i);
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}


 


 


 

原文地址:https://www.cnblogs.com/bluewelkin/p/4056390.html