zoukankan      html  css  js  c++  java
  • Java的Thread和Runnable

    第一、Runnable、Thread中的run方法和自定义的run方法之间的关系:

     1 interface Runnable{
     2     public abstract void run();
     3 }                                //remove method body
     4 
     5 public class Thread implements Runnable {
     6     private Runnable target;                //封装
     7     public Thread(Runnable target,String name){        //构造函数,name是线程的名称
     8         init(target);
     9     }
    10     
    11     private void init(Runnable target2) {    //检验关口,给属性赋值
    12         this.target = target;
    13     }
    14     
    15     public void run() {
    16         if(target != null){
    17             target.run();    //此run方法指的是自定义的run方法,即Runable中的run方法
    18                     //整个过程中,只有一个对象,只有这个对象有能力调用自定
    19                     //义的run方法。
    20         }    
    21     }    
    22 }
    23 class MyThread implements Runnable{
    24     public void run() {                        //自定义的run方法
    25         
    26     }
    27 }

    第二、Thread和Runnable比较

        1)Thread

     1 package com.threaddemo;
     2 
     3 class MyThread extends Thread{
     4     private int ticket = 5;
     5     public void run(){
     6         for(int i=0;i<100;i++){
     7             if(ticket>0){
     8                 System.out.println(ticket--);
     9             }
    10         }
    11     }
    12 }
    13 
    14 public class ThreadDemo04 {
    15 
    16     public static void main(String[] args) {
    17         MyThread mt1 = new MyThread();
    18         MyThread mt2 = new MyThread();
    19         MyThread mt3  =new MyThread();
    20         mt1.start();
    21         mt2.start();
    22         mt3.start();
    23     }
    24 
    25 }

      2)

     1 package com.runnabledemo;
     2 
     3 class MyThread implements Runnable{
     4     private int ticket =5;
     5     public void run(){
     6         for(int i=0;i<100;i++){
     7             if(ticket>0){
     8                 System.out.println(ticket--);
     9             }
    10         }
    11     }
    12 }
    13 
    14 public class RunnableDemo02 {
    15 
    16     public static void main(String[] args) {
    17         MyThread my = new MyThread();
    18         new Thread(my).start();
    19         new Thread(my).start();
    20         new Thread(my).start();
    21     }
    22 }

    从以上两个程序可知:在使用Runable的整个过程中,只产生一个能操作ticket的对象,实现多个线程共同处理同一资源(ticket),即实现资源的共享;

    而在使用Thread时,每一个New都会产生一个拥有自己的ticket的对象,即每个对象都有各自的ticket,各操作各的,三个ticket数值变化互不影响。

  • 相关阅读:
    linux常用命令:
    解决css添加padding后元素变长的问题
    Hbase常用命令
    集群部署的三种方式(hadoop集群部署三种方式)
    linux编译安装指定依赖的软件包
    vue使用Element隐藏侧边栏进度条
    css相对于父容器,固定放在底部并撑满
    java中23种设计模式
    adb remount'的作用是什么?在什么情况下有用?
    java常用http请求库
  • 原文地址:https://www.cnblogs.com/XuGuobao/p/7200679.html
Copyright © 2011-2022 走看看