You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
37 lines
606 B
37 lines
606 B
2 years ago
|
1.使用synchronized关键字同步线程
|
||
|
package step2;
|
||
|
|
||
|
public class Task {
|
||
|
|
||
|
public static void main(String[] args) {
|
||
|
|
||
|
final insertData insert = new insertData();
|
||
|
|
||
|
for (int i = 0; i < 3; i++) {
|
||
|
new Thread(new Runnable() {
|
||
|
public void run() {
|
||
|
insert.insert(Thread.currentThread());
|
||
|
}
|
||
|
}).start();
|
||
|
}
|
||
|
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class insertData {
|
||
|
|
||
|
public static int num = 0;
|
||
|
|
||
|
/********* Begin *********/
|
||
|
public synchronized void insert(Thread thread) {
|
||
|
|
||
|
for (int i = 0; i <= 5; i++) {
|
||
|
num++;
|
||
|
System.out.println(num);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/********* End *********/
|
||
|
}
|
||
|
|