除了实现多线程的两种方式,与解决线程安全问题的三种方式还有一些小的方法,如:setName赋值名字方法,getName得到名字方法如:RunnableImpl r = new RunnableImpl(); //创立三个线程Thread t = new Thread(r);Thread t1 = new Thread(r);Thread t2 = new Thread(r);t.setName("线程1").start;t1.setName("线程2").start;t2.setName("线程3").start;或者直接:Thread t = new Thread(r,"线程1");Thread t1 = new Thread(r,"线程2");Thread t2 = new Thread(r,"线程3");在这里,在加深一下:直接用匿名方法来做new Thread(r,"线程1").start; 比较简单一下
扩展:
死锁的实现:死锁:资源有限!多个线程中同步代码块形成了嵌套关系。都在抢夺另外一个资源!public class Test03 { public static void main(String[] args) { String left = "筷子左"; String right = "筷子右"; new Thread() { @Override public void run() { while(true) { synchronized (left) { System.out.println("我抢到了筷子左,正在等待筷子右"); synchronized (right) { System.out.println("我抢到了筷子右,开吃!"); } } } } }.start(); new Thread() { @Override public void run() { while(true) { synchronized (right) { System.out.println("班长抢到了筷子右,正在等待筷子左"); synchronized (left) { System.out.println("班长抢到了筷子左,开吃!"); } } } } }.start(); }}死锁,了解就好!