如何创建java程序的线程
方式一:继承于Thread类
- class PrintNum extends Thread{
- public void run(){
- //子线程执行的代码
- for(int i = 1;i <= 100;i++){
- if(i % 2 == 0){
- System.out.println(Thread.currentThread().getName() + ":" + i);
- }
- }
- }
- public PrintNum(String name){
- super(name);
- }
- }
- public class TestThread {
- public static void main(String[] args) {
- PrintNum p1 = new PrintNum("线程1");
- PrintNum p2 = new PrintNum("线程2");
- p1.setPriority(Thread.MAX_PRIORITY);//10
- p2.setPriority(Thread.MIN_PRIORITY);//1
- p1.start();
- p2.start();
- }
- }
复制代码
方式二:实现Runnable接口
- class SubThread implements Runnable{
- public void run(){
- //子线程执行的代码
- for(int i = 1;i <= 100;i++){
- if(i % 2 == 0){
- System.out.println(Thread.currentThread().getName() + ":" + i);
- }
- }
- }
- }
- public class TestThread{
- public static void main(String[] args){
- SubThread s = new SubThread();
- Thread t1 = new Thread(s);
- Thread t2 = new Thread(s);
-
- t1.setName("线程1");
- t2.setName("线程2");
-
- t1.start();
- t2.start();
- }
- }
复制代码
两种方式的对比:联系:class Thread implements Runnable
比较哪个好?实现的方式较好。①解决了单继承的局限性。②如果多个线程有共享数据的话,建议使用实现方式,同时,共享
数据所在的类可以作为Runnable接口的实现类。
线程里的常用方法:start() run() currentThread() getName() setName(String name) yield() join() sleep() isAlive()
getPriority() setPriority(int i); wait() notify() notifyAll() |
|