多线程【基础】


1、线程概念

简单理解,一个客户端可以同时做很多事,就是多线程

2、创建线程(三种方法)

  1. 继承线程类,例如:

    //继承Thread类,并且重写run方法
    public class LitterThread extends Thread {
    	private String myName;
    	private int num=5;
    
    	public String getMyName() {
    		return myName;
    	}
    
    	public void setMyName(String myName) {
    		this.myName = myName;
    	}
    	
    	@Override
    	public void run() {
    		super.run();
    		while(num>0)
    		{
    			System.out.println("现在是"+this.myName+"执行啦");
    			num--;
    		}
    	}
    }
    
    //实例化该线程并且调用改start方法
    public class TestThread {
        public static void main(String[] args) {
        	LitterThread lt1=new LitterThread();
        	lt1.setMyName("1111");
        	lt1.start();
        	LitterThread lt2=new LitterThread();
        	lt2.setMyName("2222");
        	lt2.start();   
        }
    }
    
  2. 继承线程类,例如:

    //自定义继承Runnable的类
    public class MyThread implements Runnable{
    	private String myName;
    	private int num=5;
    
    	public String getMyName() {
    		return myName;
    	}
    
    	public void setMyName(String myName) {
    		this.myName = myName;
    	}
    	
    	@Override
    	public void run() {
    		while(num>0)
    		{
    			System.out.println("现在是"+this.myName+"执行啦");
    			num--;
    		}
    	}
    	
    }
    
    //测试类用例
    public class TestThread {
        public static void main(String[] args) {
             
        	MyThread lt1=new MyThread();
        	lt1.setMyName("1111");
        	new Thread(lt1).start();
        	MyThread lt2=new MyThread();
        	lt2.setMyName("2222");
        	new Thread(lt2).start();  
        }
    }
    
  3. 匿名类

    to do more···

posted @ 2020-02-15 00:33  小七闲  阅读(192)  评论(0编辑  收藏  举报