package demo1;
public class testthread
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
// Cat cat = new Cat("花花");
// Cat cat2 = new Cat("黑黑");
Dog dog = new Dog();
// cat2.start();
// cat.start();
//dog.run();
Thread thread1 = new Thread(dog);
Thread thread2 = new Thread(dog);
Thread thread3 = new Thread(dog);
Thread thread4 = new Thread(dog);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
class Cat extends Thread{
String name;
public Cat(String name)
{
this.name = name;
}
public void run(){
while(true){
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("I'm cat "+this.name+" !");
}
}
}
class Dog implements Runnable{
private int bone = 2000;
public void run(){
while(true){
synchronized (this)
{
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
bone-=1;
System.out.println("bone :"+bone);
}
}
}
}
java线程的同步:
java任意类型的对象都有一个标志位,该标志位具有0,1两种状态,其开始状态为1,当线程执行了synchronized(object)语句后,object对象的标志位变为0的状态,直到执行完整个synchronized语句中的代码块后,该对象的标志位又回到1状态。
当一个线程执行到synchronized(object)语句的时候,先检查object对象的标志位,如果为0状态,表明有另外的线程正在执行synchronized包括的代码,那么这个线程暂时阻塞,让出cpu资源,直到另外的行程执行完相关的同步代码,并将object对象的标志位变为1状态,这个线程的阻塞就被取消,线程就能继续运行,该线程将object的标志位变为0状态,防止其他线程再进入相关的同步代码块。