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++);

}
}

你可能感兴趣的:(java,thread)