标签:静态属性 拓展 soft void runnable get 之间 family sys
实现思路:建立ThreadTest类继承Thread并建立三个线程卖100张票
public class ThreadTest extends Thread { private int i = 100; public void run() { while(true){ if(i>0) { System.out.println(Thread.currentThread().getName() + "正在售出第" + i-- + "张票"); } } } public static void main(String[] args){ ThreadTest th = new ThreadTest(); new Thread(th).start(); new Thread(th).start(); new Thread(th).start(); } }
体会:三个线程之间无序卖票,且线程之间无干扰。
实现思路:建立ThreadTest类实现Runnable接口并建立一个对象的三个线程卖100张票
public class ThreadTest implements Runnable { private int i = 100; public void run() { while(true){ if(i>0) { System.out.println(Thread.currentThread().getName() + "正在售出第" + i-- + "张票"); } } } public static void main(String[] args){ ThreadTest th = new ThreadTest(); new Thread(th).start(); new Thread(th).start(); new Thread(th).start(); } }
个人体会:三个线程共同卖出100张票,线程之间无序执行,th就相当于一个火车站,然后三个售票员卖100张票
思路:建立三个ThreadTest类的对象当做三个火车站,每个火车站一个售票员,把票变为静态属性
public class ThreadTest extends Thread { static int i = 100; public void run() { while(true){ if(i>0) { System.out.println(Thread.currentThread().getName() + "正在售出第" + i-- + "张票"); } } } public static void main(String[] args){ ThreadTest th1 = new ThreadTest(); new Thread(th1).start();//一火车站一售票员 ThreadTest th2 = new ThreadTest(); new Thread(th2).start(); ThreadTest th3 = new ThreadTest(); new Thread(th3).start(); } }
标签:静态属性 拓展 soft void runnable get 之间 family sys
原文地址:http://www.cnblogs.com/20158424-hxlz/p/6526850.html