复制 public class T {
// 不加 volatile,程序永远不会停下
/* volatile */ boolean running = true ;
public void m () {
System . out . println ( "m start" );
while (running) {
System . out . println ( "running" );
try {
TimeUnit . SECONDS . sleep ( 1 );
} catch ( InterruptedException e) {
e . printStackTrace ();
}
}
System . out . println ( "m end" );
}
public static void main ( String [] args) {
T t = new T() ;
/*
需要注意,如果直接执行 t.m() 而不是另起线程,那么无论是否加 volatile,程序都不会停下,循环判断中的 running 一直为 true
*/
new Thread(t :: m) . start ();
try {
TimeUnit . SECONDS . sleep ( 5 );
} catch ( InterruptedException e) {
e . printStackTrace ();
}
t . running = false ;
System . out . println ( t . running );
}
}
复制 public class T {
volatile private int count = 0 ;
// 不加 synchronized,最终结果远小于 10 * 10000
public /* synchronized */ void m () {
for ( int i = 0 ; i < 10000 ; i ++ ) {
count ++ ;
}
}
public static void main ( String [] args) {
T t = new T() ;
List < Thread > threadList = new ArrayList <>();
for ( int i = 0 ; i < 10 ; i ++ ) {
threadList . add ( new Thread(t :: m , "Thread" + i) );
}
threadList . forEach (Thread :: start);
threadList . forEach (thread -> {
try {
thread . join ();
} catch ( InterruptedException e) {
e . printStackTrace ();
}
});
System . out . println ( "count: " + t . count );
}
}
复制 public class T {
private AtomicInteger count = new AtomicInteger( 0 ) ;
public void m () {
for ( int i = 0 ; i < 10000 ; i ++ ) {
count . getAndIncrement ();
}
}
public static void main ( String [] args) {
T t = new T() ;
List < Thread > threadList = new ArrayList <>();
for ( int i = 0 ; i < 10 ; i ++ ) {
threadList . add ( new Thread(t :: m , "Thread" + i) );
}
threadList . forEach (Thread :: start);
threadList . forEach (thread -> {
try {
thread . join ();
} catch ( InterruptedException e) {
e . printStackTrace ();
}
});
System . out . println ( "count: " + t . count . get ());
}
}
复制 public void m() {
for ( int i = 0 ; i < 10000 ; i ++ ) {
if ( count . get () < 1000 ) {
count . getAndIncrement ();
}
}
}