#線程相關知識
1.建立線程的兩種方式java
2.實現Runnable接口的好處安全
#多線程併發安全之賣票多線程
/** * Created by yuandl on 2016-09-30. */
public class RunnableTest implements Runnable {
private int tick = 60;
@Override
public void run() {
while (true) {
if (tick == 0) {
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "=========" + tick--);
}
}
public static void main(String[] args) {
RunnableTest runnableTest=new RunnableTest();
new Thread(runnableTest).start();
new Thread(runnableTest).start();
}
}複製代碼
打印結果併發
Thread-1=========11
Thread-1=========10
Thread-0=========9
Thread-1=========8
Thread-0=========7
Thread-0=========6
Thread-1=========5
Thread-0=========4
Thread-1=========3
Thread-0=========2
Thread-1=========1
Thread-0=========0
Thread-0=========-1
Thread-0=========-2
Thread-0=========-3ide
發現問題,賣票居然出現了負數,這確定是有問題的this
同步代碼塊的格式spa
synchronized(對象)
{
須要被同步的代碼 ;
}線程
同步的好處:解決了線程的安全問題。code
同步的前提:同步中必須有多個線程並使用同一個鎖。對象
#最終線程安全同步的代碼
/** * Created by yuandl on 2016-09-30. */
public class RunnableTest implements Runnable {
private int tick = 60;
@Override
public void run() {
while (true) {
synchronized (this) {
if (tick == 0) {
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "=========" + tick--);
}
}
}
public static void main(String[] args) {
RunnableTest runnableTest=new RunnableTest();
new Thread(runnableTest).start();
new Thread(runnableTest).start();
}
}複製代碼
Thread-1=========10
Thread-1=========9
Thread-1=========8
Thread-1=========7
Thread-1=========6
Thread-1=========5
Thread-1=========4
Thread-1=========3
Thread-1=========2
Thread-1=========1
Process finished with exit code 0
完美解決以上問題