线程同步可以有两种方式
一、采用同步代码块:就是用synchronized申明一个互斥变量
class aa
{
public static void main(String[] args)
{
TestThread tt = new TestThread();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
}
}
class TestThread implements Runnable
{
int tickets = 10;
String str = new String("");
public void run()
{
synchronized (str)
{
while (tickets > 0)
{
System.out.println("TestThread: "
+ Thread.currentThread().getName() + "the tickets = "
+ tickets--);
}
}
}
二、采用同步函数:用在方法前加上synchronized。同步函数其实是把this作为互斥变量
class aa
{
public static void main(String[] args)
{
TestThread tt = new TestThread();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
}
}
class TestThread implements Runnable
{
int tickets = 10;
String str = new String("");
public void run()
{
while (true)
{
sale();
}
}
synchronized public void sale()
{
while (tickets > 0)
{
System.out.println("TestThread: "
+ Thread.currentThread().getName() + "the tickets = "
+ tickets--);
}
}
阅读(658) | 评论(0) | 转发(0) |