本文主要是介绍java SE多线程(关于runnable接口实现多线程),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
创建多线程时,如果使用同一个runnable对象,则多个线程共享一个runnable资源
<pre name="code" class="java">public class MyThread implements Runnable {int i;@Overridepublic void run() {while(true){try {Thread.sleep((long)Math.random()*1000);System.out.println(Thread.currentThread().getName()+i++);} catch (InterruptedException e) {e.printStackTrace();}if( i == 20)break;}}
}
public class ThreadTest {public static void main(String[] args) {MyThread mt = new MyThread();Thread t1 = new Thread(mt,"1:");Thread t2 = new Thread(mt,"2:");t1.start();t2.start();}
}
运行结果如下图:
这篇关于java SE多线程(关于runnable接口实现多线程)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!