一.关于线程
- 线程是执行java程序代码的基本单位
- java线程是java平台的一部分
二.java中的线程编程
Thread类
java中的线程已被封装为Thread类,void start()方法就是启动线程的方法,调用后会让线程去执行指定的方法。void run()是其中一个方法,start()方法会把它作为线程的起点。
只要让一个类去继承Thread类,然后去覆盖其中的run()方法,那么就可以控制线程了
1 public class UseThread{ 2 public static void main(String[] args){ 3 MyThread thread = new MyThread(); 4 thread.run; 5 } 6 } 7 class MyThread extends Thread{ 8 public void run(){ 9 System.out.println("This is a thread code"); 10 } 11 }
可是一个类只能实现单继承,如果继承了线程类后,则无法继承其它类,于是这时候最好是使用接口。java提供了Runnable()接口,它包括了run()方法在内。Thread类中含有Runnable属性,构造方法可以是Thread(Runnable),只要Runnable不为null,那么就可以启用run()方法。
public class UseThread {
public static void main(String[] args){ MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.run(); } } class MyRunnable implements Runnable{ public void run(){ System.out.println("这是一个线程代码"); } }
package study_java; public class Threadagain { public static void main(String[] args){ Threadone threadone = new Threadone(); Threadone threadtwo = new Threadone("线程1"); threadtwo.start(); threadone.start(); threadone.printcurrentthread(); threadtwo.printcurrentthread(); } } class Threadone extends Thread{ Threadone(){ super(); } Threadone(String name){ super(name); } public void run(){ System.out.println("这个线程是: " + this.getName()); } public void printcurrentthread(){ Thread threading = Thread.currentThread(); String threadingname = threading.getName(); System.out.println(threadingname); } }
package study_java; public class Inner { public static void main(String[] args){ PrintCurrentThread printer = new PrintCurrentThread(); //匿名内部类 Runnable runnable = new Runnable(){ public void run(){ PrintCurrentThread p = new PrintCurrentThread(); p.printcurrrentthread(); } }; Thread thread = new Thread(runnable,"线程-1"); thread.start(); printer.printcurrrentthread(); } } class PrintCurrentThread{ public void printcurrrentthread(){ Thread currentthread = Thread.currentThread(); String threadname = currentthread.getName(); System.out.println(threadname); } }
package study_java; public class Threadagain { public static void main(String[] args){ Threadone threadone = new Threadone(); Thread thread = new Thread( threadone); thread.start(); } } class Threadone implements Runnable{ public void run(){ System.out.println("这是一个我自己创建的线程"); } }
1 package study_java; 2 3 public class Threadagain { 4 public static void main(String[] args){ 5 6 Thread thread = new Thread( new Runnable() { 7 public void run(){ 8 System.out.println("这是一个我自己创建的线程"); 9 } 10 }); 11 thread.start(); 12 } 13 14 } 15 class Threadone implements Runnable{ 16 public void run(){ 17 System.out.println("这是一个我自己创建的线程"); 18 } 19 }
使用匿名类