day19 thread

thread

Common methods in threads

sleep()

join()
joinThread.join() waits for the execution of the joinThread thread to complete, waits for the joinThread thread for
joinThread.jnin(10)up to 10ms, and then continues to execute

isAlive()
determines the alive state of the thread

interrupt() ———————————

//中断线程的状态
obj.interrupt();
//其他对象调用,更改标记,不改变状态
thread.interrupt();
//自己调用,真正中断线程
this.interrupt();

isInterrupted()

return boolean //判断该对象是否被中断
obj.isInterrupted()

interrupted()

//判断该对象是否被中断 之后会清空状态置为false
 boolean obj.interrupted()     


thread synchronization

Pass parameters to overload a constructor with parameters
Then , declare the parameters as global variables

synchronized()

//同步代码块
//Object obj 锁对象->引用类型 
synchronized(obj){
    //代码块
}
  • If the lock object is not obtained, it will enter the lock pool and enter the blocking state
  • If the lock object is held, synchronizedall code in the execution will be executed
  • After the execution is completed, release the lock object and the threads in the lock pool, and re-scramble for the right to use the lock object
//同步方法
public synchronized void test(){
}
  • When synchronizing the lock object in the methodthis
  • Lock objects are generally shared data
  • Synchronized code blocks are generally in the run()middle, multi-threading becomes single-threaded, synchronized代码块and the less code in the middle, the better.


thread communication

Synchronized code block
– lock object. wait()
– lock object. notify() – lock object. notify(
)
– lock object. notifyAll()

wait()

obj.wait();
  • After the call, enter the object waiting pool
  • After the call wait(), the CPU and the lock object will be released

notify()

//将等待区的一个线程拿到锁池
 obj.notify();
//将等待区的所有线程拿到锁池
 obj.notifyAll();


deadlock



Set thread priority

//最大优先级
thread.setPriority(1~10);
//获取当前线程优先级
thread.getPrioity();
//------------------
//让出CPU使用权,让给优先级高的线程
Thread.yield();//运行 -> 就绪