zoukankan      html  css  js  c++  java
  • 线程的2种创建方式

    package thread;
    /**
     * 线程有2中创建方式
     * 方式一:
     * 继承Thread 并重写run方法,
     * 并再run方法中添加线程要执行的代码
     * 
     * @author 清风已来
     *
     */
    
    public class ThreadDemo1 {
    public static void main(String[] args) {
    	Thread t1 = new MyThread1();
    	Thread t2 = new MyThread2();
    	/**
    	 * 需要注意,启动线程要调用该线程的start方法
    	 * 而不是调用run方法,当start方法调用后,线程纳入线程调用
    	 * 一旦该线程获取了CPU的时间片段后,该线程会自动调用
    	 */
    	t1.start();//启动1线程
    	t2.start();//启动2线程
       }
    }
    /*此种创建线程的方式有2个不足之处:
     * 1:由于JAVA是单继承的这就导致了若继承了Thread
     * 就不能再继承其他类,在实际开发中会有诸多不边。
     * 2:定义线程的同时在run方法中定义了线程要执行的任务
     * 这就导致了线程与任务有一个必然的耦合关系,不利于
     * 线程的重用
     * 强藕合 会让该对象不灵活   依赖度太大,不利于线程的重用
     * 
     */
    class MyThread1 extends Thread{
    	public void run() {
    		for(int i=0;i<100;i++) {
    			System.out.println("你谁啊?");
    		}
    	}
    }
    class MyThread2 extends Thread{
    	public void run() {
    		for (int i=0;i<100;i++) {
    			System.out.println("我是查水表的");
    		}
    	}
    }
    

      

    package thread;
    
    /**
    * 线程有2中创建方式 方式二: 实现Runnable接口单独定义线程任务
    *
    * 
    * @author 清风已来
    *
    */
    
    public class ThreadDemo2 {
    public static void main(String[] args) {
    Runnable r1 = new MyRunnable1();
    Runnable r2 = new MyRunnable2();
    
    Thread t1 =new Thread(r1);
    Thread t2 =new Thread(r2);
    
    t1.start();
    t2.start();
    
    }
    }
    
    class MyRunnable1 implements Runnable {
    public void run() {
    for (int i = 0; i < 1000; i++) {
    System.out.println("你是谁啊?");
    }
    }
    }
    
    class MyRunnable2 implements Runnable {
    public void run() {
    for (int i = 0; i < 1000; i++) {
    System.out.println("我是查水表的!");
    }
    }
    
    }
    

      

  • 相关阅读:
    Flask-SQLAlchemy 学习总结
    ubuntu安装redis
    PostgreSQL在Ubuntu上安装指南
    Linux(Ubuntu)下MySQL的安装与配置
    python wechat_sdk间接性的出现错误OfficialAPIError: 40001,说access_token已过期或者不是最新的。
    django不要设置datetime字段auto_now=True
    python 装饰器和 functools 模块
    关于 Python Iterator 协议的一点思考
    python中的enumerate函数
    8 种常被忽视的 SQL 错误用法
  • 原文地址:https://www.cnblogs.com/xyk1987/p/8259621.html
Copyright © 2011-2022 走看看