#线程相关知识
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
完美解决以上问题