2016-7-5 Java : Thread
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2016-7-5 Java : Thread相关的知识,希望对你有一定的参考价值。
两种方式:
1.继承Thread 2.实现Runnable
1.
class MyThread extends Thread{ public static int num = 0; @Override public void run() { // TODO Auto-generated method stub while(num<100) { System.out.println(Thread.currentThread().getName() + " -> "+ num++); } } } public class Test { public static void main(String[] args) { MyThread thread01 = new MyThread(); MyThread thread02 = new MyThread(); thread01.start(); thread02.start(); } }
2.
class YourThread implements Runnable { private static int num = 0; @Override public void run() { // TODO Auto-generated method stub while (num < 100) { System.out.println(Thread.currentThread().getName() + " -> " + num++); } } } public class Test { public static void main(String[] args) { Thread thread01 = new Thread(new YourThread(),"t01"); Thread thread02 = new Thread(new YourThread(),"t02"); thread01.start(); thread02.start(); } }
这种同步问题不会每次都出现.
以上是关于2016-7-5 Java : Thread的主要内容,如果未能解决你的问题,请参考以下文章
Java Thread 的 run() 与 start() 的区别
python opencv error “parallel_impl.cpp (240) WorkerThread 155: Can‘t spawn new thread: res = 11“(代码片
C++ std::this_thread::yield()函数(线程抑制线程让步让出时间片)volatile