java.lang.Runnable

public class TaskClass implements Runnable{
@Override
public void run(){
}
}
// Create an instance of TaskClass
TaskClass task = new TaskClass(...);
// Create a thread
Thread thread = new Thread(task);
// Start a thread
thread.start();

java.lang.Thread

//非实例

Thread.sleep(milliseconds)

//实例

Thead.join()  //加入主线程的等待

Thread.isAlive() //该线程是否活跃

Thread.interrupt() 如果线程当前处于就绪或运行状态,则设置其中断标志;如果线程当前被阻止,则唤醒该线程并进入就绪状态,并引发java.io.InterruptedException。

  • interrupt() 方法只是改变中断状态而已,它不会中 断一个正在运行的线程。
  • 这一方法实际完成的是,给受阻塞的线程发出一个 中断信号,这样受阻线程就得以退出阻塞的状态。
  • 如果线程没有被阻塞,这时调用 interrupt()将不起 作用,直到执行到wait(),sleep(),join()时,才马上会抛 出 InterruptedException。
  • 当线程由于被调用了sleep(), wait(), join()等方法而进入阻塞状态;若此时 调用线程的interrupt()将线程的中断标记设为true。由于处于阻塞状态, 中断标记会被清除,同时产生一个InterruptedException异常。将 InterruptedException放在适当的为止就能终止线程

Thread.stop() //会导致死锁

利用isInterrupt & interrupt来结束线程

 

keyword:synchronized

public synchronized void deposit(double amount)

在函数前加入关键字 synchronized 保证只有一个线程能够访问函数。

public void xMethod() {
synchronized (this) {
// method body
}
}

在函数中加入关键字  synchronized 保证只有一个线程能够访问该代码段。

 

java.util.concurrent.locks.Lock

java.util.concurrent.locks.ReentrantLock

 

ReentrantLock(true) 公平锁

ReentrantLock(false) 非公平锁

使用锁:

private static Lock lock = new ReentrantLock();
public void deposit( int amount ){
lock.lock();
...
lock.unlock();
}

读锁、写锁:

lock.readLock.lock()

lock.readLock.unlock()

lock.writeLock.lock()

lock.writeLock.unlock()

读写互斥、写写互斥、读读共享


0 条评论

发表评论

Avatar placeholder