继承Thread和继承Runnable

首先,我们都知道可以通过实现Runnable,来进行资源共享

public class Runnabl_Test implements Runnable {

	int ticket = 10;

	public void run() {
		for (int i = 0; i < 10; i++) {
			if (ticket > 0) {
				System.out.println(Thread.currentThread().getName() + " " + ticket--);

			}
		}
	}

	public static void main(String[] args) {
		Runnabl_Test rt = new Runnabl_Test();
		Thread thread = new Thread(rt);
		Thread thread2 = new Thread(rt);
		thread.setName("A");
		thread2.setName("B");
		thread.start();
		thread2.start();
	}

}

输出结果:


从结果可以看出,资源是进行共享的。

但是这种操作其实是有问题的,如果经过多次测试,就会可能出现下面的情况

继承Thread和继承Runnable_第1张图片

将count--操作的位置改变一下就行

for (int i = 0; i < 5; i++) {
		{
				ticket--;
				System.out.println(Thread.currentThread().getName() + " " + ticket);
		}

如果想要一个线程执行完了,再让另一个线程执行,该怎样办?

synchronized


这时候就可以使用了,要注意的是,synchronized修饰的对象是代码块和方法,不能修饰变量,比如int a = 0;synchronized(a)这样是不被允许的。下面是结果。


那继承Thread类能否实现资源共享

public class Thread_Test extends Thread {

	int count = 10;

       public void run() {
		method();

	}

	  public void method() {
		for (int i = 0; i < 5; i++) {
			count--;
			System.out.println(Thread.currentThread().getName() + "    " + count);
		}
	}

	public static void main(String[] args) {
	
		Thread_Test thread = new Thread_Test();
		thread.setName("A");
		thread.start();

		Thread_Test thread2 = new Thread_Test();
		thread2.setName("B");
		thread2.start();
		}

}

继承Thread和继承Runnable_第2张图片

可以明显看出,资源没有实现共享。那么能否让继承Thread而实现资源共享呢?

可以从上面的结果看出,是由于B线程的插队,而导致资源没有共享,那能否使用synchronized来实现资源共享?

synchronized public void method() {
		for (int i = 0; i < 5; i++) {
			 count--;
			System.out.println(Thread.currentThread().getName() + "    " + count);
		}
	}

结果:


资源并没有进行共享。







你可能感兴趣的:(Java)