线程的组成
1.cpu时间片:操作系统为每个线程分配执行时间。
2.运行数据:
堆空间:存储线程需使用的对象,多个线程可以共享堆中的对象。
栈空间:存储线程需使用的局部变量,每个线程都有独立的栈。
Java实现多线程
1…继承Thread:
控制台打印的顺序,不代表这个线程在CPU里执行的顺序
//1:新建线程对象
//2:调用start方法
public class TestThread {
public static void main(String[] args) {
//可以创建多个线程
//线程之间是并行
//创建多个线程对象
MyThread mt1 = new MyThread();
MyThread mt2 = new MyThread();
//运行线程
mt1.start();
mt2.start();
}
}
//实现多线程
//继承Thread
class MyThread extends Thread{
//覆盖run()方法
public void run() {
System.out.println("这是一个线程");
}
}
2…实现Runnable
**启动一个线程,必须通过Thread的start方法
//1:新建线程对象
//2:新建Thread对象
//3:通过Thread对象调用start方法
public class TestRunnable {
public static void main(String[] args) {
MyRunnable mr1 = new MyRunnable("线程一");
MyRunnable mr2 = new MyRunnable("线程二");
//启动线程,必须new thread对象
Thread th1 = new Thread(mr1);
th1.start();
Thread th2 = new Thread(mr2);
th2.start();
}
}
//实现多线程方式
class MyRunnable implements Runnable{
private String name;
public MyRunnable() {
super();
// TODO Auto-generated constructor stub
}
public MyRunnable(String name) {
super();
this.name = name;
}
//重写run方法
public void run() {
for(int i =0;i<10;i++) {
System.out.println(name+i);
}
}
}
线程的API
1:让当前执行的线程休眠
1:Thread.sleep(long millis);//让当前执行的线程休眠
public class Test1 {
public static void main(String[] args) throws InterruptedException {
System.out.println("开始");
//让当前线程休眠5秒
Thread.sleep(5000);
System.out.println("结束");
}
}
2.表示放弃当前时间片,交给cpu接着选择
2:Thread.yield();//表示放弃当前时间片,交给cpu接着选择
public class TestThread2 {
public static void main(String[] args) {
MyThread1 mt1 = new MyThread1();
mt1.start();
}
}
class MyThread1 extends Thread {
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println("这是一个线程MyThread1 " + i);
// 主动放弃时间片
Thread.yield();
}
}
}
setPriority(int 1-10);//设置线程在JVM里面的优先级