package com.test;import java.util.Date;publicclassTestThread{publicstaticvoidmain(String[] args){TestThread1 testThread1 =newTestThread1();TestThread2 testThread2 =newTestThread2();//排对等待CPU分配testThread1.start();testThread2.start();}}classTestThread1extendsThread{@Overridepublicvoidrun(){for(int i =0; i <3; i++){System.out.println("1的第"+i+"次北京时间:"+newDate());try{sleep(3000);//线程休息1秒}catch(InterruptedException e){e.printStackTrace();}}}}classTestThread2extendsThread{@Overridepublicvoidrun(){for(int i =0; i <3; i++){System.out.println("2的第"+i+"次北京时间:"+newDate());try{sleep(2000);//线程休息2秒}catch(InterruptedException e){e.printStackTrace();}}}}//结果1的第0次北京时间:Wed Mar 0314:47:54 CST 20212的第0次北京时间:Wed Mar 0314:47:54 CST 20212的第1次北京时间:Wed Mar 0314:47:56 CST 20211的第1次北京时间:Wed Mar 0314:47:57 CST 20212的第2次北京时间:Wed Mar 0314:47:58 CST 20211的第2次北京时间:Wed Mar 0314:48:00 CST 2021
实现Runnable接口创建线程
package com.test;publicclassTestRunnableimplementsRunnable{@Overridepublicvoidrun(){for(int i =0; i <2; i++){System.out.println("第一"+i+"次来了");}}publicstaticvoidmain(String[] args){TestRunnable testRunnable =newTestRunnable();testRunnable.run();//或者Thread thread =newThread(testRunnable)thread.start();}}//结果
第一0次来了
第一1次来了