zoukankan      html  css  js  c++  java
  • 多线程的实现方式

     1 public class ThreadDemo1 {
     2     public static void main(String[] args) {
     3         /*多线程的实现方式一:
     4          *   1.写一个Thread的子类2.重写run方法3.创建子类对象4.启动线程
     5          */
     6         ThreadClassBase p=new ThreadClassBase();
     7         p.setName("线程一");
     8         p.start();
     9         ThreadClassBase p1=new ThreadClassBase();
    10         p1.setName("线程二");
    11         p1.start();
    12         
    13     }
    14 
    15 }
    16 
    17 //Thread子类
    18 public class ThreadClassBase extends Thread {
    19     @Override
    20     public void run() {
    21         for(int i=0;i<100;i++){
    22             System.out.println(this.getName()+":"+i);
    23         }
    24     }
    25 
    26 }
     1 public class ThreadDemo2 {
     2     public static void main(String[] args) {
     3         /*多线程的实现方式二:
     4          * 1.实现Runnable接口2.重写接口中run方法
     5          * 3.创建Thread对象,将实现接口的类作为参数给Thread构造方法
     6          * 4.启动线程,运行重写接口中的run方法
     7          */
     8         ThreadClassBase2 tcb=new ThreadClassBase2();
     9         Thread t=new Thread(tcb);
    10         t.setName("线程一");
    11         t.start();
    12         Thread t1=new Thread(tcb);//如果构造方法中参数不同,可以另外创建一个对象
    13         t1.setName("线程二");
    14         t1.start();
    15     }
    16 
    17 }
    18 
    19 //实现Runnable接口的类
    20 public class ThreadClassBase2 implements Runnable {
    21 
    22     public void run() {
    23         for(int i=0;i<100;i++){
    24             Thread t=Thread.currentThread();
    25             System.out.println(t.getName()+":"+i);
    26         }
    27         
    28     }
    29 
    30 }

     有第二种实现方式的原因:

      解决Java中单一继承的问题

  • 相关阅读:
    vue 封装 全局弹窗 js-dom
    vue 封装时间戳 用过滤方法封装
    前端上传img 并且添加水印
    原生ajax 封装
    vue filters 过滤用法 时间戳方法
    node+mysql+vue 搭建前后端分离基础框架
    基于jq div拉拽功能
    进程间通信方式+线程间通信方式
    只能生成栈对象和只能生成堆对象
    linux的基础命令行和shell的区别
  • 原文地址:https://www.cnblogs.com/abtious/p/12294842.html
Copyright © 2011-2022 走看看