"Java Summary-Threads" Java Multi-threading usage

Source: Internet
Author: User

Two ways to create threads inherit the thread class
    • Defines a class that inherits the thread class
    • To override the Run method in the thread class in a subclass
    • The object that creates the thread subclass is the threading object created
    • Call the Start method of the Thread object, start the thread, and call the Run method automatically
publicclass TestThread extends Thread {    publicstaticvoidmain(String[] args) {        new TestThread();        tt.start();    }    //重写run方法    publicvoidrun() {        System.out.println("run");    }}
Implementing the Runnable Interface
    • Self Subclass Implementation Runnable Interface
    • override the Run method in interface
    • to create a thread object with the thread parameter constructor
    • pass an object of the Runnable interface subclass as an argument
    • li> call the Start method of the thread class to open the thread
publicclass TestThread {    publicstaticvoid main(String[] args) {        new T();        new Thread(t);        tt.start();    }}class T implements Runnable {    @Override    publicvoid run() {        System.out.println("run");    }}

Multiple threads should be implemented using the Runnable interface, enabling multiple inheritance

getName()setName(String name);//设置线程名字staticcurrentThread();//返回当前线程
setPriority(intnew);//改变线程的优先级getPriority()返回线程的优先级
Thread.sleep(10);//让线程睡10秒,阻塞
Thread synchronization
synchroized(对象) {    //需要同步的代码}
public synchroinized void show(String name) {    ...}
Thread Communication
wait();//让当前线程等待notify();//唤醒线程notifyAll();//唤醒正在排队的所有线程

"Java Summary-Threads" Java Multi-threading usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.