java线程笔记(二)

(一)同步方法:(可以自己比较同步和不同步关系)
class One
{
synchronized void display(int num)
{
System.out.println(" "+num);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("中断");
}
System.out.println("完成");
}
}
class Two implements Runnable
{
int number;
One one;
Thread t;
public Two(One one_num,int n)
{
one=one_num;
number=n;
t=new Thread(this);
t.start();
}
public void run()
{one.display(number);}
}
public class Synch
{
public static void main(String args[])
{
One one=new One();
int digit=10;
Two s1=new Two(one,digit++);
Two s2=new Two(one,digit++);
Two s3=new Two(one,digit++);

}
}

(二)同步代码块:
Synchronized(object){//同步代码},object为被同步对象的引用。
class One
{
void display(int num)
{
System.out.println(" "+num);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{System.out.println("中断");}
System.out.println("完成");
}
}
class Two implements Runnable
{
int number;
One one;
Thread t;
public Two(One one_num,int n)
{
one=one_num;
number=n;
t=new Thread(this);
t.start();
}
public void run()
{
synchronized(one)
{one.display(number);}
}
}
class SynchBlock
{
public static void main(String args[])
{
One one=new One();
int digit=10;
Two s1=new Two(one,digit++);
Two s2=new Two(one,digit++);
Two s3=new Two(one,digit++);

}
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值