public class Main { public static void main(String[] args) { Runnable test = new TestThread(); new Thread(test).start(); new Thread(test).start(); } }
/** * * @author Jerome */ public class TestThread implements Runnable { int count = 0; @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(count++); } } }
运行结果如下:
两个线程共享了变量count;
2、线程通过wait进入阻塞状态,即等待获取锁,一般的锁为this(当前线程)必须调用notify唤醒之后才能继续被分配cpu资料运行;
synchronized (this) { this.wait(); } this.notify();
wait()和notify()因为会对对象的“锁标志”进行操作,所以它们必须在synchronized函数或synchronized代码块中进行调用。
3、终止线程有3中方法,设置标志位(run方法运行正常退出),调用interrupt(),调用stop(),后面两种是让线程抛出异常而退出,不推荐;
4、sleep不会释放锁标志;
5、所谓的线程之间保持同步,是指不同的线程在执行同一个对象的同步代码块时,因为要获得对象的同步锁而互相牵制,不同对象不存在同步的问题;
6、synchronized 关键字能够修饰一个对象实例中的函数或者代码块。 在一个非静态方法中 this 关键字表示当前的实例对象。 在一个 synchronized 修饰的静态的方法中,这个方法所在的类使用 Class 作为实例对象