Java_log2000_线程2

来源:互联网 发布:男性发型设计软件 编辑:程序博客网 时间:2024/06/05 22:38

线程篇entry2

关键词: 线程与进程; Thread类; Runnable接口;

1.

public class MyThread extends Thread {    public static void main ( String args[] ) {                        Thread a = new MyThread();                         //(1)        a.start();                                            //(2)        System.out.println("This is main thread.");     //(3)    }    public void run() {        System.out.println("This is another thread."); //(4)    }                                                          }
    2.
public class MyThread implements Runnable {    public static void main ( String args[] ) {                        MyThread my = new MyThread();                          //(1)        Thread a = new Thread(my);                             //(2)        a.start();                                                //(3)        System.out.println("This is main thread.");        //(4)    }    public void run() {        System.out.println("This is another thread.");    //(5)    }                                                          }
    3.
class MyThread extends Thread{  public void run(){    while(true)    {      System.out.println(Thread.currentThread().getName()+" is running");    }  }}public class TestMyThread{  public static void main(String[] args){      new MyThread().run();//new MyThread().start();            while(true){        System.out.println("main1 thread is running");      }  }}
    4.
class Resource implements Runnable {    public int i;                                                                  public  Resource(int _i){        i = _i;    }    public void run(){        while(true){            if (i>0){             i--;             System.out.println(Thread.currentThread().getName()+"   "+i);            }          else                break;        }    }}public class TestThread{    public static void main(String[] args){        Resource m = new Resource(100);        Thread t1 = new Thread(m);        Thread t2 = new Thread(m);        t1.start();        t2.start();    }}
原创粉丝点击