java多线程之线程同步
线程同步
定义:同步是指在同一时间段内只能运行一个线程。
分类:同步方法、同步块。
作用:安全解决共享问题。
同步块:
语法:
synchronized (同步对象) {
需要同步的代码;
}
例子:
public class ThreadDemo implements Runnable{
private int ticket = 5;
public void run(){
for(int i=1;i<=5;i++){
synchronized (this){
if(ticket>0)
{
Thread.sleep(1000);
System.out.println("卖票:ticket="+ticket--);
}
}
}
}
同步方法:
语法:
synchronized 方法返回值 方法名称 (参数列表) {
}
例子:
public class ThreadDemo implements Runnable{
private int ticket = 5;
public void run(){
for(int i=1;i<=5;i++)
{
this.saleTicket();
}
}
public synchronized void saleTicket() {
if(ticket>0)
{
Thread.sleep(1000);
System.out.println("卖票:ticket="+ticket--);
}
}
同步方法完整示例:
public class Timer {
private static int num = 0;
public synchronized void add(String name) { //在执行这个方法过程中,当前对象被锁定
num ++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name + " 你是第"+num + "个使用Timer的线程");
}
}
public class TestSync implements Runnable{
Timer timer = new Timer();
public static void main(String[] args) {
TestSync testSync = new TestSync();
Thread t1 = new Thread(testSync);
Thread t2 = new Thread(testSync);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run() {
timer.add(Thread.currentThread().getName());
}
}