多线程结合案例详解
package com.ywx; class MyThread extends Thread{ private String name; public MyThread(String name){ this.name=name; } public void run(){ for(int i=0;i<10;i++){ System.out.println(name+"运行i="+i); } } } public class ThreadDemo1 { public static void main(String[] args) { MyThread mt1 = new MyThread("线程A"); MyThread mt2 = new MyThread("线程B"); mt1.run(); mt2.run(); } }
package com.ywx; class MyThread extends Thread{ private String name; public MyThread(String name){ this.name=name; } public void run(){ for(int i=0;i<10;i++){ System.out.println(name+"运行i="+i); } } } public class ThreadDemo1 { public static void main(String[] args) { MyThread mt1 = new MyThread("线程A"); MyThread mt2 = new MyThread("线程B"); mt1.start(); mt2.start(); } }运行结果:
package com.ywx; class MyThread implements Runnable{ private String name; public MyThread(String name){ this.name=name; } public void run(){ for(int i=0;i<10;i++){ System.out.println(name+"运行i="+i); } } } public class RunnableDemo { public static void main(String[] args) { MyThread mt1 = new MyThread("线程A"); MyThread mt2 = new MyThread("线程B"); Thread thread1 = new Thread(mt1); Thread thread2 = new Thread(mt2); thread1.start(); thread2.start(); } }
package com.ywx; class MyThread extends Thread{ private int ticket=5; private String name; public MyThread(String name){ this.name=name; } public void run(){ for(int i=0;i<100;i++){ if(this.ticket>0){ System.out.println(name+"卖票,实票ticket="+ticket--); } } } } public class ThreadDemo { public static void main(String[] args) { MyThread mt1 = new MyThread("线程A"); MyThread mt2 = new MyThread("线程B"); mt1.run(); mt2.run(); } }
package com.ywx; class MyThread implements Runnable{ private int ticket=5; public void run(){ for(int i=0;i<100;i++){ if(this.ticket>0){ System.out.println("卖票,实票ticket="+ticket--); } } } } public class RunnableDemo { public static void main(String[] args) { MyThread mt1 = new MyThread(); Thread thread1 = new Thread(mt1); Thread thread2 = new Thread(mt1); thread1.start(); thread2.start(); } }