public class ThreadOwn extends Thread {
@Override
public void run() {
}
}
实现Runnable接口
public class RunnableOwn implements Runnable {
@Override
public void run() {
}
}
其实继承Thread与实现Runnable接口原理上是一样的,查看Thread源码可知
public class Thread implements Runnable {
/* Make sure registerNatives is the first thing <clinit> does. */
private static native void registerNatives();
static {
registerNatives();
}
Thread也是实现了Runnable接口
创建Thread匿名子类
public class Test {
public static void main(String[] args) {
ConcurrentHashMap<Integer, Integer> objectObjectConcurrentHashMap = new ConcurrentHashMap<>();
new Thread() {
@Override
public void run() {
while (true) {
for (int i = 0; i < 100; i++) {
Integer o = objectObjectConcurrentHashMap.get(i);
if (o == null) {
o = 0;
}
objectObjectConcurrentHashMap.put(i, i + o);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while (true) {
for (int i = 0; i < 100; i++) {
Integer o = objectObjectConcurrentHashMap.get(i);
if (o == null) {
o = 0;
}
objectObjectConcurrentHashMap.put(i, i + o);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while (true) {
for (int i = 0; i < 100; i++) {
Integer o = objectObjectConcurrentHashMap.get(i);
if (o == null) {
o = 0;
}
objectObjectConcurrentHashMap.put(i, i + o);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
CloneUtil.clone(objectObjectConcurrentHashMap).forEach((key, value) -> {
System.out.println(key + ":" + value);
});
System.out.println("----------------------");
}
}
}.start();
}
}
此方法不紧实现了Thread匿名子类,重点在于验证ConcurrentHashMap线程安全,可以实现读写分离
实现Callable接口
public class CallableOwn implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return 0;
}
}
public class CallableTest {
public static void main(String[] args) {
// 与Runable相比,明显可以看出此方法有返回值,并且抛出异常可捕获
CallableOwn callableOwn = new CallableOwn();
// 将此Callable接口实现类的对象作为参数传递到FutureTask构造器中,创建FutureTask对象
FutureTask<Integer> futureTask = new FutureTask(callableOwn);
new Thread(futureTask).start();
try {
// 获取Callable中Call方法的返回值
Integer sum = futureTask.get();
System.out.println("总和为"+sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}