Java 自定义线程
public class thread_01 extends Thread{ /* (non-Javadoc) * @see java.lang.Thread#run() */ @Override //把自定义线程的任务代码写在run方法中。 public void run() { for(int i = 0 ; i < 100 ; i++){ System.out.println("自定义线程:"+i); } } public static void main(String[] args) { // TODO Auto-generated method stub thread_01 thread_01 =new thread_01(); //线程1 thread_01.run(); for(int i = 0 ; i < 100 ; i++){ //线程2 System.out.println("main:"+i); } } }
自定义线程:97 自定义线程:98 自定义线程:99 main:0 main:1 main:2 main:3
public class thread_01 extends Thread{ /* (non-Javadoc) * @see java.lang.Thread#run() */ @Override //把自定义线程的任务代码写在run方法中。 public void run() { for(int i = 0 ; i < 100 ; i++){ System.out.println("自定义线程:"+i); } } public static void main(String[] args) { // TODO Auto-generated method stub //创建线程更对象 thread_01 thread_01 =new thread_01(); //线程1 //调用start方法启动线程 thread_01.start(); for(int i = 0 ; i < 100 ; i++){ //线程2 System.out.println("main:"+i); } } }
main:21 main:22 main:23 main:24 自定义线程:18 main:25 main:26 main:27 自定义线程:19 main:28 main:29 main:30 main:31 自定义线程:20 自定义线程:21 main:32 自定义线程:22 自定义线程:23 自定义线程:24 自定义线程:25
/* 需求: 模拟QQ视频与聊天同时在执行。 */ class TalkThread extends Thread{ @Override public void run() { while(true){ System.out.println("hi,你好!开视频呗..."); } } } class VideoThread extends Thread{ @Override public void run() { while(true){ System.out.println("视频视频...."); } } } public class Demo2 { public static void main(String[] args) { TalkThread talkThread = new TalkThread(); talkThread.start(); VideoThread videoThread = new VideoThread(); videoThread.start(); } }
线程的生命周期
public class thread_03 extends Thread{ @Override public void run() { for(int i=0;i<100;i++) { System.out.println(i); } } public static void main(String[] args) { // TODO Auto-generated method stub thread_03 th1=new thread_03(); System.out.println("线程的名字"+th1.getName()); thread_03 th2=new thread_03(); System.out.println("线程的名字"+th2.getName()); thread_03 th3=new thread_03(); System.out.println("线程的名字"+th3.getName()); //thread_03.start(); } }
线程的名字Thread-0 线程的名字Thread-1 线程的名字Thread-2
public class thread_03 extends Thread{ public thread_03 (String name) { super(name); } @Override public void run() { for(int i=0;i<100;i++) { System.out.println(i); } } public static void main(String[] args) { // TODO Auto-generated method stub thread_03 th1=new thread_03("线程1"); System.out.println("线程的名字: "+th1.getName()); thread_03 th2=new thread_03("线程2"); System.out.println("线程的名字: "+th2.getName()); thread_03 th3=new thread_03("线程3"); System.out.println("线程的名字 :"+th3.getName()); //thread_03.start(); } }
线程的名字: 线程1 线程的名字: 线程2 线程的名字 :线程3