您的位置:首页 > 其它

Thread 和 Runnable 的一些区别

2016-06-06 15:09 190 查看
package com.lsh.java8.thread;

import java.util.concurrent.atomic.AtomicInteger;

public class MySimpleRunnable implements Runnable
{
private static AtomicInteger index = new AtomicInteger();

private AtomicInteger value = new AtomicInteger(10);

@Override
public void run() {
for(int i = 0 ; i < 10 && value.get() >= 0; i++)
{
System.out.println(Thread.currentThread().getName() + ": value = " + value.getAndDecrement());
}
}

public static void main(String[] args)
{
Thread thread = new Thread(new MySimpleRunnable());
new Thread(thread, "My_runnable" + index.getAndIncrement()).start();
new Thread(thread, "My_runnable" + index.getAndIncrement()).start();
new Thread(thread, "My_runnable" + index.getAndIncrement()).start();
}
}


console

My_runnable0: value = 10

My_runnable0: value = 7

My_runnable2: value = 8

My_runnable2: value = 5

My_runnable2: value = 4

My_runnable2: value = 3

My_runnable2: value = 2

My_runnable2: value = 1

My_runnable2: value = 0

My_runnable1: value = 9

My_runnable0: value = 6

package com.lsh.java8.thread;

import java.util.concurrent.atomic.AtomicInteger;

public class MySimpleThread extends Thread
{
private static AtomicInteger index = new AtomicInteger();

private AtomicInteger value = new AtomicInteger(10);

@Override
public void run()
{
for(int i = 0 ; i < 10 && value.get() >= 0; i++)
{
System.out.println( this.getName() +  ": value = " + value.getAndDecrement());
}
}

public MySimpleThread(String name)
{
this.setName(name + index.getAndIncrement());
}

public static void main(String[] args)
{
MySimpleThread thread1 = new MySimpleThread("My_thread_");
MySimpleThread thread2 = new MySimpleThread("My_thread_");
MySimpleThread thread3 = new MySimpleThread("My_thread_");
thread1.run();
thread2.run();
thread3.run();
}
}


console

My_thread_0: value = 10

My_thread_0: value = 9

My_thread_0: value = 8

My_thread_0: value = 7

My_thread_0: value = 6

My_thread_0: value = 5

My_thread_0: value = 4

My_thread_0: value = 3

My_thread_0: value = 2

My_thread_0: value = 1

My_thread_1: value = 10

My_thread_1: value = 9

My_thread_1: value = 8

My_thread_1: value = 7

My_thread_1: value = 6

My_thread_1: value = 5

My_thread_1: value = 4

My_thread_1: value = 3

My_thread_1: value = 2

My_thread_1: value = 1

My_thread_2: value = 10

My_thread_2: value = 9

My_thread_2: value = 8

My_thread_2: value = 7

My_thread_2: value = 6

My_thread_2: value = 5

My_thread_2: value = 4

My_thread_2: value = 3

My_thread_2: value = 2

My_thread_2: value = 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: