您的位置:首页 > 其它

线程

2016-05-30 20:17 323 查看
进程:正在运行的程序。

线程:每一个运行的程序都是一个进程,在一个进程中还可以有多个执行单元同时运行,这些执行单元可以看做是程序执行的一条条线索,被称为线程。

线程的创建

1、单线程

public class T1{

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread t=new MyThread();
t.run();
while(true){
System.out.println("Main方法在运行");
}
}

}
class MyThread{
public void run(){
while(true){
System.out.println("MyThread类的方法在运行");
}
}
}

运行结果,它会进入一个死循环。
多线程(继承Thread类):

public class T1{

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread t=new MyThread();
t.start();//开启线程
while(true){
System.out.println("Main方法在运行");
}
}

}
class MyThread extends Thread{
public void run(){
while(true){
System.out.println("MyThread类的方法在运行");
}
}
}在多线程中,main()方法和MyThread类的run()方法却可以同时运行,互不影响,这正是单线程和多线程的区别。
实现Runnable接口创建多线程

     因为Java中只支持单继承,一个类一旦继承了父类就无法再继承Thread类,,为了克服这种弊端,Thread类提供了另外一个构造方法Thread(Runnable target),其中Runnable是一个接口,它只有一个run()方法,当用Runnable时,可以用run()方法,不用Thread类的run()方法。

public class T1{

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread mt=new MyThread();
Thread t=new Thread(mt);
t.start();//开启线程
while(true){
System.out.println("Main方法在运行");
}
}

}
class MyThread implements Runnable{
public void run(){
while(true){
System.out.println("MyThread类的方法在运行");
}
}
}直接继承Thread和实现Runnable接口区别:
public class T1{

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
new MyThread().start();
new MyThread().start();
new MyThread().start();
new MyThread().start();
}

}
class MyThread extends Thread{
private int mt=100;
public void run(){
while(true){
if(mt>0)
{
Thread th=Thread.currentThread();//获取当前线程
String th_name=th.getName();//获取当前线程的名字
System.out.println(th_name+"正在发售第"+mt+"张票");
}
}
}
}

public class T1{

/**
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread my=new MyThread();
new Thread(my,"窗口1").start();
new Thread(my,"窗口2").start();
new Thread(my,"窗口3").start();
new Thread(my,"窗口4").start();
}

}
class MyThread implements Runnable{
private int mt=100;
public void run(){
while(true){
if(mt>0)
{
Thread th=Thread.currentThread();//获取当前线程
String th_name=th.getName();//获取当前线程的名字
System.out.println(th_name+"正在发售第"+mt+"张票");
}
}
}
}

Runnable好处:
1、适合多个相同程序代码的线程去处理同一个资源的情况,把线程同代码、数据有效的分离,很好地体现了面向对象的设计思想。

2、可以避免由于java的单继承带来的局限性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: