Java基础:多线程

进程和线程:进程可以理解为是正在执行的程序。线程是最小的分派代码单元,程序可以一次执行多项任务。

线程的状态:running(运行),read to run(准备就绪),suspended(挂起),resumed(继续执行),blocked(阻塞状态),terminated(终止)。

示例代码:

  1. class MyThread implements Runnable{    //实现Runnable接口
  2.     String thrdName;
  3.     
  4.     MyThread(String name){                       //构造
  5.         thrdName=name;
  6.     }
  7.     
  8.     public void run(){                                    //线程开始执行
  9.         System.out.println(thrdName+" starting.");
  10.         
  11.         try{
  12.             for(int i=0;i<10;i++){
  13.                 Thread.sleep(400);                       //线程休眠时间(毫秒)
  14.                 System.out.println("In "+thrdName+"i is "+i);
  15.             }
  16.         }catch(InterruptedException e){
  17.             System.out.println(e);
  18.         }
  19.         System.out.println(thrdName+" termination.");
  20.     }
  21. }
  22. class UseThreads{
  23.     public static void main(String[] args){
  24.         System.out.println("Main thread starting.");
  25.         
  26.         MyThread mt=new MyThread("Child #1");       //创建一个可运行的对象
  27.         Thread newThread=new Thread(mt);               //构造一个线程
  28.         
  29.         newThread.start();                             //开始运行线程
  30.         
  31.         for(int i=0;i<50;i++){
  32.             try{
  33.                 Thread.sleep(100);                  //休眠时间
  34.             }catch(InterruptedException e){  //捕获异常
  35.                 System.out.println(e);
  36.             }
  37.         }
  38.         
  39.         System.out.println("Main thread ending");
  40.         System.out.println("Child #1×Ô¼ºÔËÐÐ");
  41.         mt.run();  //直接调用run()方法
  42.     }
  43. }
  44. ------------------------------------------------------------------------------------------------------
  45. 创建多线程:
  46. class MyThreadsss implements Runnable{         //实现Runnable接口
  47.     Thread thrd;                                     //Thread对象
  48.     MyThreadsss(String name){          //构造
  49.         thrd=new Thread(this,name);    //创建时运行
  50.         thrd.start();
  51.     }
  52.     
  53.     public void run() {             //run()方法
  54.         System.out.println(thrd.getName()+" starting.");
  55.         try {
  56.             for(int i=0;i<10;i++) {
  57.                 Thread.sleep(400);             //线程休眠
  58.                 System.out.println("In "+thrd.getName()+"i is "+i);
  59.             }
  60.         }catch(InterruptedException e) {
  61.             System.out.println(e);
  62.         }
  63.         System.out.println(thrd.getName()+" terminating.");
  64.     }
  65.     
  66. }
  67. public class MoreThreads {
  68.     public MoreThreads() {
  69.         
  70.     }
  71.   
  72.     public static void main(String[] args) {
  73.     
  74.         System.out.println("Main thread starting.");
  75.         
  76.         MyThreadsss mt1=new MyThreadsss("Child#1");   //多个子线程
  77.         MyThreadsss mt2=new MyThreadsss("Child#2");
  78.         MyThreadsss mt3=new MyThreadsss("Child#3");
  79.      
  80.         do {
  81.             try {
  82.                 Thread.sleep(100);  //线程休眠
  83.             } catch (InterruptedException e) {             
  84.                 e.printStackTrace();
  85.                 System.out.println("Main thread interrupted.");
  86.             }
  87.         }while(mt1.thrd.isAlive()||mt2.thrd.isAlive()||mt3.thrd.isAlive()); //isAlive()确定线程是否结束,运行返回true,结束返回false
  88.         
  89.         mt1.thrd.join();//等待,直到指定线程结束
  90.         
  91.        mt1.thrd.setPriority(Thread.NORM_PRIORITY+2); //设置线程优先级
  92.        mt2.thrd.setPriority(Thread.NORM_PRIORITY-2);
  93.     
  94.         System.out.println("Main thread ending.");
  95.     }
  96. }
  97. ------------------------------------------------------------------------------------------------
  98. 线程通信:notify()   wait()之间的通信
  99. class TickTock{
  100.     String state;
  101.     
  102.     synchronized void tick(boolean running) {  //synchronized修饰方法,方法同步
  103.         if(!running) {
  104.             state="ticked";
  105.             notify(); //通知其他等待的线程
  106.             return;
  107.         }
  108.         System.out.println("Ticked ");
  109.         
  110.         try {
  111.             Thread.sleep(500);
  112.         } catch (InterruptedException e1) {
  113.            
  114.             e1.printStackTrace();
  115.         }
  116.                 
  117.         state="ticked";
  118.         notify(); //通知其他等待的线程
  119.         
  120.         try {
  121.             while(!state.equals("tocked")) {
  122.                 wait();  //等待
  123.             }
  124.         }catch(InterruptedException e) {
  125.             e.printStackTrace();
  126.         }
  127.     }
  128.     
  129.     
  130.     synchronized void tock(boolean running) {  //同步方法
  131.         if(!running) { 
  132.             state="tocked";
  133.             notify();  //通知其他等待的线程
  134.             return;
  135.         }
  136.         
  137.         System.out.println("Tocked");
  138.         
  139.         try {
  140.             Thread.sleep(500);  //休眠
  141.         } catch (InterruptedException e1) {
  142.           
  143.             e1.printStackTrace();
  144.         }
  145.         
  146.         state="tocked";
  147.         notify();  //通知其他等待的线程
  148.         
  149.         try {
  150.             while(!state.equals("ticked")) {
  151.                 wait();  //等待
  152.             }
  153.         } catch (InterruptedException e) {
  154.          
  155.             e.printStackTrace();
  156.         }
  157.     }
  158.     
  159. }
  160. class MyThreadtc implements Runnable{   //实现Runnable接口
  161.     Thread thrd;
  162.     TickTock ttOb;
  163.     
  164.     MyThreadtc(String name,TickTock tt){
  165.         thrd=new Thread(this,name);    //创建对象时运行
  166.         ttOb=tt;
  167.         thrd.start();
  168.     }
  169.     
  170.     public void run() {    //run()方法
  171.         if(thrd.getName().compareTo("Tick")==0) {
  172.             for(int i=0;i<5;i++) {
  173.                 ttOb.tick(true);
  174.             }
  175.             ttOb.tick(false);
  176.         }else {
  177.             for(int i=0;i<5;i++) {
  178.                 ttOb.tock(true);
  179.             }
  180.             ttOb.tock(false);
  181.         }
  182.     }
  183. }
  184. public class ThreadCom {
  185.     public ThreadCom() {
  186.      
  187.     }
  188.     public static void main(String[] args) {
  189.      
  190.         TickTock tt=new TickTock();
  191.         MyThreadtc mt1=new MyThreadtc("Tick",tt);
  192.         MyThreadtc mt2=new MyThreadtc("Tock",tt);
  193.         
  194.         try {
  195.             mt1.thrd.join();  //等待,知道线程结束
  196.             mt2.thrd.join();
  197.         } catch (InterruptedException e) {
  198.           
  199.             e.printStackTrace();
  200.         }
  201.     }
  202. }
    --------------------------------------------------------------------------------------
  203. 线程的挂起,继续执行和停止:
  204. class MyThreadsrs implements Runnable{
  205.     Thread thrd;
  206.     
  207.     boolean suspended;    //为true时,线程挂起
  208.     boolean stopped;         //为true时,线程终止
  209.     
  210.     MyThreadsrs(String name){
  211.         thrd=new Thread(this,name);
  212.         suspended=false;
  213.         stopped=false;
  214.         thrd.start();
  215.     }
  216.     
  217.     public void run() {
  218.  
  219.         System.out.println(thrd.getName()+" starting.");
  220.         
  221.         try {
  222.             for(int i=1;i<1000;i++) {
  223.                 System.out.print(i+" ");
  224.                 if((i%10)==0) {
  225.                     System.out.println();
  226.                     Thread.sleep(250);
  227.                 }
  228.                 
  229.                 synchronized(this) {  //同步代码块检查suspended和stopped
  230.                     while(suspended) {
  231.                         wait();
  232.                     }
  233.                     if(stopped) break;
  234.                 }
  235.             }
  236.             
  237.         }catch(InterruptedException e) {
  238.             e.printStackTrace();
  239.         }
  240.         
  241.         System.out.println(thrd.getName()+" ending");        
  242.     }
  243.     
  244.     synchronized void mystop() {  //stop()方法
  245.         stopped=true;
  246.         suspended=false;
  247.         notify();
  248.     }
  249.     
  250.     synchronized void mysuspend() { //suspend()方法
  251.         suspended=true;
  252.     }
  253.     
  254.     synchronized void myresume() { //resume()方法
  255.         suspended=false;
  256.         notify();
  257.     }
  258. }
  259. public class Suspend {
  260.     public Suspend() {
  261.      
  262.     }
  263.     public static void main(String[] args) {
  264.         
  265.         MyThreadsrs ob1=new MyThreadsrs("My Thread");
  266.         
  267.         try {
  268.             Thread.sleep(1000);
  269.             
  270.             ob1.mysuspend();
  271.             System.out.println("Suspending thread.");
  272.             Thread.sleep(1000);
  273.             
  274.             ob1.myresume();
  275.             System.out.println("Resuming thread.");
  276.             Thread.sleep(1000);
  277.             
  278.             ob1.mysuspend();
  279.             System.out.println("Suspending thread.");
  280.             Thread.sleep(1000);
  281.             
  282.             ob1.myresume();
  283.             System.out.println("Resuming thread.");
  284.             Thread.sleep(1000);
  285.             
  286.             ob1.mysuspend();
  287.             System.out.println("Stopping thread.");
  288.             ob1.mystop();
  289.             
  290.         } catch (InterruptedException e) {
  291.         
  292.             e.printStackTrace();
  293.         }
  294.         
  295.         try {
  296.             ob1.thrd.join();
  297.         } catch (InterruptedException e) {
  298.            
  299.             e.printStackTrace();
  300.         }
  301.     }
  302. }
  303. --------------------------------------------------------------------------------------
  304. 主线程:
  305. public class UseMain {
  306.     public UseMain() {      
  307.     }
  308.     public static void main(String[] args) {
  309.       
  310.         Thread thrd;
  311.         
  312.         thrd=Thread.currentThread();                   //主线程
  313.         System.out.println("Main thread is called:"+ thrd.getName());  //获取线程名
  314.         System.out.println("Priority:"+thrd.getPriority());  //获取线程优先级别
  315.         System.out.println();
  316.         
  317.         System.out.println("Setting name and priority.");
  318.         thrd.setName("Thread #1");                         //设置主线程名字
  319.         thrd.setPriority(Thread.NORM_PRIORITY+3); //设置主线程优先级
  320.         
  321.         System.out.println("Main thread is called:"+ thrd.getName());
  322.         System.out.println("Priority:"+thrd.getPriority());
  323.         System.out.println();        
  324.     }
  325. }

猜你喜欢

转载自blog.csdn.net/QQhelphelp/article/details/87984129