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