Creating and related methods thread - Java multi-threaded (1)

Thread and the thread can learn basic concept here is not described in detail here in the operating system

Create a multithreaded

A way to inherit the Thread class
1. Create a class inherits from Thread subclass
run () 2. Thread the rewrite -> operating declare this thread executing run () in
3. Create an object subclass of the Thread class
4. this object calls start ()

//1.创建一个继承于Thread类的子类
class   ThreadTest extends  Thread{
    public void run(){
       // 2.重写Thread的run()-->将此线程执行的操作声明在run()中
        for(int i=1;i<=100;i++){
            if(i%2==0)
                System.out.print(i+" ");
        }
    }
}

public class MyThread1 {
    public static void main(String[] args) {
        //3.创建Thread类的子类的对象
        ThreadTest ts=new ThreadTest();
        //4.通过此对象调用start():①启动当前线程 ②调用当前线程的run()
        ts.start();
        //不能通过直接调用run()来启动线程
        //再启动一个线程
        ThreadTest t2=new ThreadTest();
        t2.start();
        for(int i=1;i<=100;i++){
            if(i%2!=0)
                System.out.print(i+" ");
        }
    }
}

The results presented here will produce interactive phenomenon, ts when the thread starts running, the main thread is still down implementation rather than tune out the method and other methods as finished to return to the main function to continue, cpu will take turns to allocate resources in order to achieve concurrent threads
Here Insert Picture Description

important point:

  1. If you call yourself a manual run () method, then just ordinary method, does not start multi-thread mode.
  2. run () method by the JVM to call, when to call, perform process control has an operating system CPU
    scheduling decisions.
  3. Want to start a multi-threaded, you must call the start method.
  4. A thread object can only be called once start () method to start, if repeated calls, and more will be thrown
    exception "IllegalThreadStateException".

Second way: implement Runnable

  1. Subclassing, implement Runnable.
  2. run method Runnable interface override sub-category.
  3. Thread by thread object creation of Parametric constructor.
  4. The subclass object passed to Runnable interface Thread class constructor as an actual parameter.
  5. Thread class method calls start: open thread calls the run method subclass of Runnable interface.
class MThread implements Runnable{
    // 2. 实现类去实现Runnable中的抽象方法:run()
    public void run(){
        for(int i=0;i<100;i++){
            if(i%100==0)
                System.out.println(Thread.currentThread().getName()+i);
        }
    }
}
public class newThread {
    public static void main(String[] args) {
        //3. 创建实现类的对象
        MThread mThread =new MThread();
        //4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
        Thread t1=new Thread(mThread);
        // 5. 通过Thread类的对象调用start()
        t1.start();//调用了runnable类型的target的run()这里的target就是传递进去的实现了runnable接口的对象
    }
}

If you want to create multiple threads just then create a Thread object to the incoming object implementation class

Thread common method

Thread the test commonly used methods:

  1. start (): Start the current thread; the current thread calls the run ()
  2. run (): usually need to override this method in the Thread class, declare the operation will create a thread to be executed in this method
  3. currentThread (): Static method that returns the current thread executes code
  4. getName (): Gets the name of the current thread
  5. setName (): set the name of the current thread
  6. yield (): The current release of executive power cpu
  7. join (): b calling thread in a thread in the join (), this time a thread enters the blocked state until after completion of thread b fully implemented before the end of a thread blocked.
  8. stop (): Obsolete. When you do this method, force the end of the current thread.
  9. sleep (long millitime): Let the current thread "sleep" specified millitime milliseconds. Millitime milliseconds in the specified time, the current thread is blocked.
  10. isAlive (): determine whether the survival of the current thread
class Threadtest3 extends Thread{
    public void run(){
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0)
                System.out.println(Thread.currentThread().getName()+" "+getPriority()+i + " ");
            if(i%20==0)
                //yield();释放cpu执行权 但可能刚释放 cpu又分配给你了
        }

    }

    //通过构造方法起名
    /*public Threadtest3(String name){
        super(name);
    }*/
}
public class ThreadMethod {
    public static void main(String[] args) {
        Threadtest3 t3=new Threadtest3();
        t3.setName("线程一");
        //t3.setPriority(Thread.MAX_PRIORITY);设置线程优先级为最高
        t3.start();
        //给主线程命名
       // Thread.currentThread().setName("主线程");
        //Thread.currentThread().setPriority(Thread.MIN_PRIORITY);设置线程优先级为最低
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) {
                try {
                    //sleep(1000);让线程进入睡眠状态cpu不会分配给它
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " "+Thread.currentThread().getPriority()+ i + " ");
            }
            if(i%20==0) {
                try {
                    t3.join();//调用线程t3,当前线程阻塞
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(t3.isAlive());//查看当前线程是否存活
    }
}

Thread priority:
1.
MAX_PRIORITY: 10
MIN _PRIORITY: 1
NORM_PRIORITY: 5 -> default priority
2. How to get and set the current thread priority:
getPriority (): Gets thread priority
setPriority (int p): priority thread

  • Description: High-priority threads to execute the right to seize the low priority thread cpu's. But only under the terms of probability, high probability of high priority threads situation
  • It is executed. When that does not mean only high-priority thread executing the low-priority thread before the execution.

Added: thread classification
in Java threads are divided into two categories: one is a daemon thread, one is user threads.

  1. In almost every aspect they are identical, the only difference is the determination of when to leave the JVM.

  2. Daemon thread is used to service user thread by calling before the start () method
    thread.setDaemon (true) can put a user thread into a daemon thread.

  3. Java garbage collection is a typical daemon thread.

  4. If the JVM is a daemon thread, the current JVM will exit.

Published 45 original articles · won praise 43 · views 7080

Guess you like

Origin blog.csdn.net/qq_42193790/article/details/104391231