Java 线程同步执行(顺序执行)

关于线程,有两种实现方法, 一种是通过继承Runnable接口,另外一种通过扩展Thread类,两者的具体差别,可参考我找的这篇文章 http://www.cnblogs.com/rollenholt/archive/2011/08/28/2156357.html 。本主主要是讲 线程的同步执行问题。。

  如果程序是通过扩展Thread类的,网上的资料说可以通过 join()函数实现,但本人亲测,此法无法通过、程序如下:

public class test1 extends Thread {
    
    public void run() {
        synchronized (this) {
            for(int i = 0; i < 6;i++) {
                System.out.println(Thread.currentThread().getName()+"   1");
                System.out.println(Thread.currentThread().getName()+"   2");
                System.out.println(Thread.currentThread().getName()+"   3");
            }
        }
    }
    
    public static void main(String arg0[]) throws InterruptedException {
        test1 test1 = new test1();
        Thread thread1 = new Thread(test1,"test1");
        Thread thread2 = new Thread(test1,"test2");
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
    }

}

可能的运行结果:

test2   1
test2   2
test2   3
test2   1
test2   2
test2   3
test2   1
test2   2
test2   3
test2   1
test2   2
test2   3
test2   1
test2   2
test2   3
test2   1
test2   2
test2   3
test1   1
test1   2
test1   3
test1   1
test1   2
test1   3
test1   1
test1   2
test1   3
test1   1
test1   2
test1   3
test1   1
test1   2
test1   3
test1   1
test1   2
test1   3

由此可见,线程的执行结果并非我们所需要的。因此,只能另寻途径。

线程的另外一种实现方法是通过实现Runnable接口,程序如下:

public class test1 implements Runnable {
    
    public void run() {
        synchronized (this) {
            for(int i = 0; i < 6;i++) {
                System.out.println(Thread.currentThread().getName()+"   1");
                System.out.println(Thread.currentThread().getName()+"   2");
                System.out.println(Thread.currentThread().getName()+"   3");
            }
        }
    }
    
    public static void main(String arg0[]) throws InterruptedException {
        test1 test1 = new test1();
        Thread thread1 = new Thread(test1,"test1");
        Thread thread2 = new Thread(test1,"test2");
        thread1.start();
        thread2.start();
    }

}

多次执行程序,并未出现异常:

test1   1
test1   2
test1   3
test1   1
test1   2
test1   3
test1   1
test1   2
test1   3
test1   1
test1   2
test1   3
test1   1
test1   2
test1   3
test1   1
test1   2
test1   3
test2   1
test2   2
test2   3
test2   1
test2   2
test2   3
test2   1
test2   2
test2   3
test2   1
test2   2
test2   3
test2   1
test2   2
test2   3
test2   1
test2   2
test2   3

 

 

posted @ 2014-07-10 15:06  叶汉城  阅读(1499)  评论(0编辑  收藏  举报