java:同步和死锁

时间:2023-03-09 18:44:14
java:同步和死锁

多个线程共享一个资源的时候需要进行同步(否则会出现错误:如负数,重复数),但是过多的同步会造成死锁.

synchronized(this)

{

}

非同步情况:

public class SyncThread implements Runnable {

	private int titick = 5;

	@Override
public void run() {
// TODO 自动生成的方法存根 for(int i = 0; i <50; i++)
{ if( this.titick > 0 )
{
//如果遇到延时情况,就会出错
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} System.out.println("卖出去第:" + this.titick-- + "张票");
}
} } } public class Demo { public static void main(String[] args) {
// TODO 自动生成的方法存根 SyncThread st = new SyncThread();
new Thread(st, "票贩子A").start();
new Thread(st, "票贩子B").start();
new Thread(st, "票贩子C").start(); } }

结果:

 java:同步和死锁 

同步情况:

public class SyncThread2 implements Runnable {

	private int titict = 5;

	@Override
public void run() {
// TODO 自动生成的方法存根 for(int i = 0; i < 50; i++)
{
synchronized(this)
{
if( this.titict > 0)
{
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println("卖出:"+ this.titict--);
}
}
} } } public class Demo2 { public static void main(String[] args) {
// TODO 自动生成的方法存根 SyncThread2 sy2 = new SyncThread2();
new Thread(sy2, "票贩子1").start();
new Thread(sy2, "票贩子2").start();
new Thread(sy2, "票贩子3").start(); } }

  结果:

java:同步和死锁