synchronized
加锁: 实现同步方法
## 测试代码
public class Test01 implements Runnable {
private int count = 0;
@Override
public synchronized void run() {
System.out.println(Thread.currentThread().getThreadGroup().getName()+"--"+Thread.currentThread().getName() + "count = " + count++);
}
public static void main(String[] args) {
Test01 t = new Test01();
for(int i = 0; i<10; i++) {
new Thread(new ThreadGroup("Test01"),t, "Thread" + i).start();
}
}
}
结果
Test01--Thread0count = 0
Test01--Thread1count = 1
Test01--Thread2count = 2
Test01--Thread3count = 3
Test01--Thread4count = 4
Test01--Thread6count = 5
Test01--Thread5count = 6
Test01--Thread7count = 7
Test01--Thread8count = 8
Test01--Thread9count = 9
QA
- 1.java实现线程
- 继承Thread类
- 实现Runnable接口
- 2.Thread类最佳实践
写的时候最好要设置线程名称 Thread.name,并设置线程组 ThreadGroup,目的是方便管理。在出现问题的时候,打印线程栈 (jstack -pid) 一眼就可以看出是哪个线程出的问题,这个线程是干什么的。