Multithreading [base]

[Base] multithreading

Tags (separated by spaces): javaweb multithreading


1, the concept of threads

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

2, create a thread (three ways)

  1. Inherit the Thread class, for example:

    //继承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. Inherit the Thread class, for example:

    //自定义继承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. Anonymous class

    to do more···

Guess you like

Origin www.cnblogs.com/inkqx/p/12303989.html