File tree Expand file tree Collapse file tree 3 files changed +13
-14
lines changed
03concurrency/0301/src/main/java/java0/conc0301 Expand file tree Collapse file tree 3 files changed +13
-14
lines changed Original file line number Diff line number Diff line change 2
2
3
3
public class DaemonThread {
4
4
5
- public static void main (String [] args ) {
6
- Runnable task = new Runnable () {
7
- @ Override
8
- public void run () {
5
+ public static void main (String [] args ) throws InterruptedException {
6
+ Runnable task = () -> {
9
7
try {
10
- Thread .sleep (5000 );
11
- } catch (InterruptedException e ) {
12
- e .printStackTrace ();
13
- }
8
+ Thread .sleep (1000 );
9
+ } catch (InterruptedException e ) {
10
+ e .printStackTrace ();
11
+ }
14
12
Thread t = Thread .currentThread ();
15
13
System .out .println ("当前线程:" + t .getName ());
16
- }
17
14
};
18
15
Thread thread = new Thread (task );
19
16
thread .setName ("test-thread-1" );
20
- thread .setDaemon (false );
17
+ thread .setDaemon (true );
21
18
thread .start ();
19
+
20
+ //Thread.sleep(2000);
22
21
}
23
22
24
23
Original file line number Diff line number Diff line change @@ -6,10 +6,10 @@ public static void main(String[] args) {
6
6
Object oo = new Object ();
7
7
8
8
MyThread thread1 = new MyThread ("thread1 -- " );
9
- thread1 .setOo (oo );
9
+ thread1 .setOo (thread1 );
10
10
thread1 .start ();
11
11
12
- synchronized (thread1 ) {
12
+ synchronized (thread1 ) { // 这里用oo或thread1/this
13
13
for (int i = 0 ; i < 100 ; i ++) {
14
14
if (i == 20 ) {
15
15
try {
@@ -40,7 +40,7 @@ public MyThread(String name) {
40
40
41
41
@ Override
42
42
public void run () {
43
- synchronized (this ) {
43
+ synchronized (this ) { // 这里用oo或this,效果不同
44
44
for (int i = 0 ; i < 100 ; i ++) {
45
45
System .out .println (name + i );
46
46
}
Original file line number Diff line number Diff line change @@ -7,7 +7,7 @@ public class Counter {
7
7
public static int B =10 ;
8
8
9
9
private volatile int sum = 0 ;
10
- public synchronized void incr () {
10
+ public void incr () {
11
11
sum =sum +1 ;
12
12
}
13
13
public int getSum () {
You can’t perform that action at this time.
0 commit comments