Java——创建进程

来源:互联网 发布:网络游戏客户端编程 编辑:程序博客网 时间:2024/06/06 16:42

关于JAVA多线程的尝试
使用多线程:


public class Main{    public static void main(String[] args)    {        MyThread thread1 = new MyThread();        thread1.start();        MyThread thread2 = new MyThread();        thread2.start();    }}class MyThread extends Thread{    private int i = 0;    public void run()    {        for(int i = 0; i < 100; ++i)        {            System.out.println(i);        }    }}

这里可以看出将会打印1到100的数字
但可以看出来,start后只是把进程作为了runable状态,并没有到running状态,其取决与处理机的调度。

还有一种建立线程的方法是实现runable接口。

class MyRunnable implements Runnable     {        private int i = 0;        @Override        public void run() {            for (i = 0; i < 100; i++) {                System.out.println(Thread.currentThread().getName() + " " + i);            }        }    }

接口作为一个必须要履行的规范,使MyRunable满足线程的run方法要求。接下来new出来thread对象即可。

public class Main    {        public static void main(String[] args)        {            Thread thread = new Thread(new MyRunnable());            thread.start();        }    }

这里就简单介绍一下线程的创立的两种方法

0 0