认识线程之Synchronized(二)
认识线程
- 使用
TimeUnit
代替Thread.sleep()
synchronized
官方文档解释
Synchronized keyword enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object’s variables are done through synchronized methods.
代码
package com.jetty.test.thread;
import java.util.concurrent.TimeUnit;
/**
* <p>
* Title:
* Description:
* Copyright: Copyright (c) 2019
* Company: ChinaSteel
* </p>
*
* @author: jetty
* @create: 2019-09-24 15:57
* @version:1.0
*/
public class Mutex {
private final static Object MUTEX = new Object();
public void accessResources(){
synchronized (MUTEX){
try {
TimeUnit.SECONDS.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
final Mutex mutex = new Mutex();
for (int i = 0;i< 15;i++){
new Thread(mutex::accessResources).start();
}
}
}
运行多个线程时,其他线程会被阻塞。
用jconsole查询
只会有一个线程进入sleeping状态,其他都进入blocked状态。
Synchronized同步的线程不可被中断
代码演示:
package com.jetty.test.thread;
import java.util.concurrent.TimeUnit;
/**
1. <p>
2. Title:
3. Description:
4. Copyright: Copyright (c) 2019
5. Company: ChinaSteel
6. </p>
7. * @author: jetty
8. @create: 2019-09-25 14:08
9. @version:1.0
*/
public class SynchronizedDefect {
public synchronized void syncMethod(){
try {
TimeUnit.HOURS.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException{
SynchronizedDefect defect = new SynchronizedDefect();
Thread thread = new Thread(defect::syncMethod,"T1");
thread.start();
TimeUnit.MILLISECONDS.sleep(2);
Thread thread2 = new Thread(defect::syncMethod,"T2");
thread2.start();
thread2.interrupt();
System.out.println(thread2.isInterrupted());
System.out.println(thread2.getState());
}
}
console结果
true
BLOCKED