java multi-threading technology

How to implement a thread

Firstly, to achieve two threads:
1, inheritance Thread;
2, Runnable class implements the interface;

 

I said here about the second, and therefore in the development of the second uses some more, to avoid inheritance or less to avoid inheritance.

RunnableDemo.java:

class RunnableDemo implements Runnable{
    public void run(){
        for(int i=0;i<100;i++){
            System.out.println("Runnable -->"+i);
        }
    }
}

Test.java:

class Test{
    public static void main(String[] args){
        RunnableDemo r = new RunnableDemo();
        Thread t = new Thread(r);
        t.start();
        
    }
}

 

operation result:

 

 

Thread of control methods

Interrupt thread

Thread.sleep()

We need to add exception handling, such as modifying RunnableDemo.java:

class RunnableDemo implements Runnable{
    public void run(){
        for(int i=0;i<100;i++){
            System.out.println("Runnable -->"+i);
            if(i == 50){
                try{
                    Thread.sleep(2000);
                }
                catch(Exception e){
                    System.out.println(e);
                }
                

            }
        }
    }
}

After the run will equal 50 when i sleep in 2 seconds.


Thread.yield()

 

 

Priority thread

Thread.getPriority()

Role: to obtain priority

class Test{
    public static void main(String[] args){
        RunnableDemo r = new RunnableDemo();
        Thread t = new Thread(r);
        t.start();
        System.out.println(t.getPriority());
        
    }
}

FIG outputted from the results, the default priority is 5:

 

 


Thread.setPrioority()

Role: Sets the maximum priority

class Test{
    public static void main(String[] args){
        RunnableDemo r = new RunnableDemo();
        Thread t = new Thread(r);
        t.start();
        t.setPriority(Thread.MAX_PRIORITY);
        System.out.println(t.getPriority());
        
    }
}

输出结果为10,说明最大优先级为10。

 

 

 

Guess you like

Origin www.cnblogs.com/endust/p/11878214.html