最近要写的程序里边要实现一个多线程发现图的算法,但是之前没有接触过图,所以先从最基础的开始学起,看一下在java里边多线程是怎么做的。
在这里发现了有人讲到runable和thread的区别,我觉得讲的很好,学习一下先
-
Runable里没有run(),而是规定implementing class必须要有run(),而且Runnable的作用仅限于此;而Thread class里有许多好用的method,比如sleep()等
-
当你发现必须extends其他某个class,而又要用线程,因为无法extends Thread,所以要implements Runnable
-
如果你的某个class A implements Runnable,则不可以直接用这个class,只能用new Thread(A)得到的thread object
-
对thread object,用start()来启动,该method会先initialize thread object,然后invoke它的run()
接下来上代码:
下边的代码里主要做了一件事情:把thisArray中的数字全部搬运到thisArray1中去
在里边count一直指向的是0,不断的移除第一个元素,所以移除的时候也是按照顺序来移除的。
package com.pclab.soapdemo;
import java.util.ArrayList;
import java.util.List;
public class TestThread {
// 公共变量
int count = 0;
static List<Integer> thisArray = new ArrayList();
List<Integer> thisArray1 = new ArrayList();
public static void main(String[] args) {
for(int i=1;i<=100;i++)
{
thisArray.add(i);
}
// new一个实现Runnable的类
TestThread test = new TestThread();
// 创建5个任务
MyRunnable myRunnable1 = test.new MyRunnable();
MyRunnable myRunnable2 = test.new MyRunnable();
MyRunnable myRunnable3 = test.new MyRunnable();
MyRunnable myRunnable4 = test.new MyRunnable();
MyRunnable myRunnable5 = test.new MyRunnable();
// 创建5个线程
new Thread(myRunnable1).start();
new Thread(myRunnable2).start();
new Thread(myRunnable3).start();
new Thread(myRunnable4).start();
new Thread(myRunnable5).start();
}
// 创建一个实现Runnable的类
class MyRunnable implements Runnable {
public void run() {
while (true) {
// 锁住的是整个MyRunnable类
synchronized (MyRunnable.class) {
if (thisArray.size() == 0) {
break;
}
int counts = thisArray.remove(count);
thisArray1.add(counts);
System.out.println(Thread.currentThread().getName() + ":count:" + (counts));
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
//测试时,线程更容易切换
Thread.yield();
}
}
System.out.println(thisArray1.toString());
System.out.println(thisArray.toString());
}
}
}