多线程的创建
一、线程的概念:
CPU时间片:CPU执行时间被划分成多个小片,把小片依次分配个等待执行的程序,通过这样的交替执行,实现多个线程的“同时运行”。
进程:执行中的程序叫进程,拥有自己独立的地址空间和资源,进程间不能直接共享资源。是操作系统调度的最小单位。
线程:同一个进程可以进一步分成更小的执行单位,叫线程,每个线程可以执行不同的任务。是CPU调度的最小单位,能够充分利用CPU资源。同一进程下的进程可以很容易的实现资源的共享。
二、java线程的继承实现(继承Thread类,并覆盖Thread类中的run()方法,即可实现多线程。)
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.jju;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author syzx
*/
public class TestThread01 {
public static void main(String[] args) {
GThread gThread1 = new GThread("ONE");
GThread gThread2 = new GThread("TWO");
gThread1.start();
gThread2.start();
System.out.println("程序执行完成!");
}
}
class GThread extends Thread{
String name;
public GThread(){
;
}
public GThread(String name){
this.name = name;
}
@Override
public void run(){
for(int i = 0; i < 10; i++){
System.out.println("线程" + name);
try {
sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(GThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
三、java线程实现接口的实现(实现Runnable接口,实现接口中的run()方法,即可实现多线程。启动方式与上边的方法不太一样)
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.jju;
import static java.lang.Thread.sleep;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author munication
*/
public class TestThread01 {
public static void main(String[] args) {
GThread gThread1 = new GThread("ONE");
GThread gThread2 = new GThread("TWO");
Thread thread1 = new Thread(gThread1);
Thread thread2 = new Thread(gThread2);
thread1.start();
thread2.start();
System.out.println("程序执行完成!");
}
}
class GThread implements Runnable{
String name;
public GThread(){
;
}
public GThread(String name){
this.name = name;
}
@Override
public void run(){
for(int i = 0; i < 10; i++){
System.out.println("线程" + name);
try {
sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(GThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}