java创建线程
- extend Thread
- implements Runnable
java多线程计算器
1 | class Caculator implements Runnable{ |
计数器
1 | public class Counter implements Runnable{ |
使用join方法
- 子线程调用join方法,让main线程等待
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16public class MySubThread extends Thread{
public void run(){
int sleepTime = 2000;
Thread.sleep(sleepTime);
System.out.println(“MySubThread run finished!”);
}
}
public class Application{
public static void main(){
MySubThread t = new MySubThread();
t.start();
// t.join();
System.out.println(“Main Thread finished!”);
}
}
线程上锁
- synchronized
- lock与ReentrantedLock
synchronized版本的计数器
1 | public class Counter implements Runnable{ |
synchronized版本的计数器之二, 使用synchronized给实例方法加锁
1 | public class Counter implements Runnable{ |
synchronized版本的计数器之三,使用synchronized修饰静态方法
1 | public class Counter implements Runnable{ |
笔记
- reentrant单词也作re-entrant,entrant为进入者、新会员的意思