就得来认识下咱们经常说道的几个概念。
进程: 是一个静态的概念,它本身是不能动的,每个进程都是有一个主方法的执行路径,这个路径就是一个具体的线程。
多线程是我们处理多任务的强有力工具。
java代码
继承Thread类实现线程实例
public class TestThread {
public static void main(String args[]) {
TestThread1 r = new TestThread1 ();
r.start();
for(int i=0; i<5; i++) {
System.out.println("Main Thread:------" + i);
}
}
}
class TestThread1 extends Thread {
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Runner1 :" + i);
}
}
}
实现Runnable接口实现多线程实例
public class TestThread {
public static void main(String args[]) {
//实例化接口实现类
Runnable1 r = new Runnable1 ();
//调用构造方法创建线程
Thread t = new Thread(r);
t.start();
for(int i=0; i<5; i++) {
System.out.println("Main Thread:------" + i);
}
}
}
class Runnable1 implements Runnable {
public void run() {
for(int i=0; i<5 i++) {
System.out.println("Runner1 :" + i);
}
}
}public static void main(String args[]) {
TestThread1 r = new TestThread1 ();
r.start();
}
public static void main(String args[]) {
//实例化接口实现类
Runnable1 r = new Runnable1 ();
//调用构造方法创建线程
Thread t = new Thread(r);
t.start();
}构造方法摘要
两者的区别:
public class thread3{
public static void main(String[] args) {
hello h1 = new hello();
hello h2 = new hello();
hello h3 = new hello();
h1.start();//每个线程都各卖了5张,共卖了15张票
h2.start();//但实际只有5张票,每个线程都卖自己的票
h3.start();//没有达到资源共享
}
}
class hello extends Thread {
public void run() {
int count = 5;
for (int i = 0; i < 7; i++) {
if (count > 0) {
System.out.println("count= " + count--);
}
}
}
}效果图
我们换位Runnable接口
class MyThread implements Runnable{
private int ticket = 5; //5张票
public void run() {
for (int i=0; i<=20; i++) {
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName()+ "正在卖票"+this.ticket--);
}
}
}
}
public class lzwCode {
public static void main(String [] args) {
MyThread my = new MyThread();
new Thread(my, "1号窗口").start();
new Thread(my, "2号窗口").start();
new Thread(my, "3号窗口").start();
}
}
效果图
所以
以上几点只是线程的基本概念。还没涉及同步,进行状态的装换。初认识java。希望大家多多指点。
原文:http://blog.csdn.net/han_yankun2009/article/details/20465917