同步的前提
必须要有两个或以上的线程 必须是所有的线程使用同一个锁这样保证同步中只能有一个线程在运行
在多线程安全问题设置同步时候注意
明确哪些代码是多线程运行代码 明确哪些是共享数据 明确多线程运行代码中,哪些语句是操作共享数据的同步的优点
解决了多线程的安全问题
同步函数所用的锁是this对象,为了保证同步代码块和同步函数所用的锁一致 ,所以
同步函数所用的锁是this对象,为了保证同步代码块和同步函数所用的锁一致 ,所以同步代码块也需要用this作为锁
class ticket implements Runnable {
private int ticket = 100;
boolean flag = true;
public void run() {
if(flag){
while (true){
//同步代码块
synchronized (this) {
if (ticket > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ " 同步代码块 " + ticket--);
}
}
}}
else
{
while(true)
{
this.show();
}
}
}
//同步函数
public synchronized void show() {
if (ticket > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 同步函数 "
+ ticket--);
}
}
}
private int ticket = 100;
boolean flag = true;
public void run() {
if(flag){
while (true){
//同步代码块
synchronized (this) {
if (ticket > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ " 同步代码块 " + ticket--);
}
}
}}
else
{
while(true)
{
this.show();
}
}
}
//同步函数
public synchronized void show() {
if (ticket > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 同步函数 "
+ ticket--);
}
}
}
public class runnabletext2 {
public static void main(String[] args) {
ticket t = new ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
/*
* Thread t3 =new Thread(t); Thread t4 =new Thread(t);
*/
t1.start();
try {
t1.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.flag = false;
t2.start();
/*
* t3.start(); t4.start();
*/
}
}
public static void main(String[] args) {
ticket t = new ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
/*
* Thread t3 =new Thread(t); Thread t4 =new Thread(t);
*/
t1.start();
try {
t1.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.flag = false;
t2.start();
/*
* t3.start(); t4.start();
*/
}
}