多线程的实现方式:demo1、demo2
demo1:继承Thread类,重写run()方法
package thread_test; public class ThreadDemo1 extends Thread { ThreadDemo1(){ } ThreadDemo1(String szName){ super(szName); } //重载run函数 public void run() { for(int count = 1 , row = 1 ; row < 10 ; row ++ , count ++) { for(int i = 0 ; i < count ; i ++) { System.out.print("*"); } System.out.println(); } } public static void main(String[] args) { //线程赛跑 ThreadDemo1 td1 = new ThreadDemo1(); ThreadDemo1 td2 = new ThreadDemo1(); ThreadDemo1 td3 = new ThreadDemo1(); td1.start(); td2.start(); td3.start(); } }
demo2:实现runnable接口,实现run()方法
package thread_test; public class ThreadDemo2 implements Runnable{ public void run() { for(int count = 1 , row = 1 ; row < 10 ; row ++ , count ++) { for(int i = 0 ; i < count ; i ++) { System.out.print("*"); } System.out.println(); } } public static void main(String[] args) { //存在线程赛跑问题 Runnable rb1 = new ThreadDemo2(); Runnable rb2 = new ThreadDemo2(); Runnable rb3 = new ThreadDemo2(); Thread td1 = new Thread(rb1); Thread td2 = new Thread(rb2); Thread td3 = new Thread(rb3); td1.start(); td2.start(); td3.start(); } }
demo3:两种方法解决进程赛跑问题
package thread_test; //两种方法解决线程赛跑 class ThreadWait extends Thread{ public ThreadWait() { } public ThreadWait(String name) { super(name); } @Override public void run() { for(int count = 1 , row = 1 ; row < 10 ; row ++ , count ++) { for(int i = 0 ; i < count ; i ++) { System.out.print("*"); } System.out.println(); } } } public class ThreadDemo3{ public static void main(String[] args) { ThreadDemo3 td = new ThreadDemo3(); // td.Method1(); td.Method2(); } public void Method1() { ThreadWait tw1 = new ThreadWait(); ThreadWait tw2 = new ThreadWait(); tw1.start(); while(tw1.isAlive()) { try{ Thread.sleep(100); }catch(Exception e){ e.getMessage(); } } tw2.start(); } public void Method2() { ThreadWait tw1 = new ThreadWait(); ThreadWait tw2 = new ThreadWait(); tw1.start(); try { tw1.join(); }catch(Exception e){ e.toString(); } tw2.start(); } }
原文地址:https://www.cnblogs.com/gaoquanquan/p/9912000.html
时间: 2024-11-03 20:57:59