第一种方法:
开线程:创建一个类,继承Thread类。实例化此类,调用此类父类的start();方法
代码:
public class FirstThread extends Thread{ @Override public void run() { for(int i = 0; i < 100; i++){ System.out.println("thread -->" + i); } }}public class Test { public static void main(String args []) { FirstThread thread = new FirstThread(); thread.start(); for(int i = 0; i < 100; i++){ System.out.println("main -->" + i); } }}
第二种方法:创建一个类,让此类implements Runnable。实例化此类和Thread类,并把实例化出来的类作为参数传给Thread类
代码:
package test;
public class RunnableImpl implements Runnable{ @Override public void run() { // TODO Auto-generated method stub for(int i = 0; i < 100 ; i++){ System.out.println("RunnableImpl -->" + i); } } }package test;
public class Test { public static void main(String args []) { RunnableImpl runnableImpl = new RunnableImpl(); Thread thread = new Thread(runnableImpl); thread.start(); }}补充:
Thread.sleep(2000); 静态方法 线程睡眠2秒,2秒休眠结束后抢到cpu会马上执行
Thread.yield(); 静态方法 结束当前线程,重新抢夺cpu,抢到cpu后会马上执行
thread.getPriority(): 获取当前线程的优先级
thread.setPriority(Thread.MAX_PRIORITY); 设置当前线程的优先级为最高级
线程的优先级最大是10 最小是1