标签:rmi policy 处理器 mit locking clear 方法区 不同的 nal
1.进程:一个在内存中运行的应用程序。每个进程都有自己独立的一块内存空间,一个进程可以有多个线程,比如在Windows系统中,一个运行的xx.exe就是一个进程。
进程中的一个执行任务(控制单元),负责当前进程中程序的执行。一个进程至少有一个线程,一个进程可以运行多个线程,多个线程可共享数据。
2.线程:与进程不同的是同类的多个线程共享进程的堆和方法区资源,但每个线程有自己的程序计数器、虚拟机栈和本地方法栈,所以系统在产生一个线程,或是在各个线程之间作切换工作时,负担要比进程小得多,也正因为如此,线程也被称为轻量级进程。
3.区别
执行过程:每个独立的进程有程序运行的入口、顺序执行序列和程序出口。但是线程不能独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制,两者均可并发执行
/**
* 线程的实现方式一:继承Thread类
*/
public class ThreadTest {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
thread1.start();
thread2.start();
}
}
class Thread1 extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++){
System.out.println(Thread.currentThread().getName());
}
}
}
class Thread2 extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++){
System.out.println(Thread.currentThread().getName());
}
}
}
2.实现Runable接口:
/**
* 线程的实现方式二:实现Runable接口
*/
public class ThreadTest2 {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
Thread thread3 = new Thread(new Thread3());
Thread thread4 = new Thread(new Thread4());
thread3.start();
thread4.start();
}
}
class Thread3 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++){
System.out.println(Thread.currentThread().getName());
}
}
}
class Thread4 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++){
System.out.println(Thread.currentThread().getName());
}
}
}
两种实现方式的共同点和区别:
区别:使用继承Thread类,类是唯一继承的原则那么该类就不能继承其他的类;而使用Runable接口的话在jiava中是可以实现的多个接口的,所以综上所述推荐使用Runable接口
public void run() {
if (target != null) {
target.run();
}
}
//target是一个Runnable对象。run()就是直接调用Thread线程的Runnable成员的run()方法,并不会新建一个线程。
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
private native void start0();//查看open jdk
while (threadTest3.value == null){
Thread.sleep(5000);
}
thread.join();
/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
*
* <p> This implementation uses a loop of {@code this.wait} calls
* conditioned on {@code this.isAlive}. As a thread terminates the
* {@code this.notifyAll} method is invoked. It is recommended that
* applications not use {@code wait}, {@code notify}, or
* {@code notifyAll} on {@code Thread} instances.
*
* @param millis
* the time to wait in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public final synchronized void join(long millis)
//从上述描述中我们可以得知join方法会一直到线程死掉
3.实现Callable接口
public class CallableTest implements Callable {
@Override
public Object call() throws Exception {
String value = "我是返回值";
System.out.println("开始执行业务逻辑");
Thread.sleep(5000);
System.out.println("执行业务逻辑完毕");
return value;
}
}
/**
* Callabel接口实现:使用FutureTask
*/
public class CallableImk {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> futureTask = new FutureTask<String>(new CallableTest());
new Thread(futureTask).start();
if(!futureTask.isDone()){
System.out.println("任务还没有完成,请稍等");
}
System.out.println(futureTask.get());
}
}
4.使用线程池的方式:
public class ThreadTest4 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
Future<String> future = executorService.submit(new CallableTest());
if(!future.isDone()){
System.out.println("waiting");
}
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}finally {
executorService.shutdown();
}
}
}
五、线程池
1.线程池的创建:
public class ThreadPoolExecutor extends AbstractExecutorService {
.....
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,
BlockingQueue<Runnable> workQueue);
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,
BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory);
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,
BlockingQueue<Runnable> workQueue,RejectedExecutionHandler handler);
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,
BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler);
...
}
参数说明:
TimeUnit.DAYS; //天
TimeUnit.HOURS; //小时
TimeUnit.MINUTES; //分钟
TimeUnit.SECONDS; //秒
TimeUnit.MILLISECONDS; //毫秒
TimeUnit.MICROSECONDS; //微妙
TimeUnit.NANOSECONDS; //纳秒
-workQueue:一个阻塞队列,用来存储等待执行的任务,这个参数的选择也很重要,会对线程池的运行过程产生重大影响,一般来说,这里的阻塞队列有以下几种选择:
ArrayBlockingQueue;
LinkedBlockingQueue;
SynchronousQueue;
注意:ArrayBlockingQueue和PriorityBlockingQueue使用较少,一般使用LinkedBlockingQueue和Synchronous。线程池的排队策略与BlockingQueue有关。
ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
ThreadPoolExecutor.DiscardPolicy:也是丢弃任务,但是不抛出异常。
ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
ThreadPoolExecutor.CallerRunsPolicy:由调用线程处理该任务
六、线程同步:
1.使用syncronized关键字:使用syncronized关键字修饰的方法是对对象的加锁;也可以修饰静态方法,当修饰静态方法是是对类加锁;也可以修饰代码块如下:
synchronized(object){
}
//同步是一种高开销的操作,因此应该尽量减少//同步的内容。
//通常没有必要同步整个方法,使用synchronized代码块同步关键代码即可。
注意:关于锁的话题,我们受限于篇幅下次再聊
七:生产者和消费者:
package Thread;
public class Person {
private String name;
private String sex;
private boolean isEmpty = true;
public synchronized void set(String name, String sex){
while (!isEmpty){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.sex = sex;
System.out.println("生产者:" + name + sex);
isEmpty = false;
this.notifyAll();
}
public synchronized void get(){
if (isEmpty){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费: " + getName() + getSex());
isEmpty = true;
this.notifyAll();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
package Thread;
public class ProductConsumerTest {
public static void main(String[] args) {
Person person = new Person();
new Thread(new Product(person)).start();
new Thread(new Consumer(person)).start();
new Thread(new Product(person)).start();
new Thread(new Consumer(person)).start();
}
}
class Product implements Runnable{
private Person person;
public Product(Person person){
this.person = person;
}
@Override
public void run() {
for (int i = 0; i < 100; i++){
if (i % 2 == 0){
person.set("teacher", "man");
}else {
person.set("mother", "women");
}
}
}
}
class Consumer implements Runnable{
private Person person;
public Consumer(Person person){
this.person = person;
}
@Override
public void run() {
for (int i = 0; i < 100; i++){
person.get();
}
}
}
参考资料:
"http://www.cnblogs.com/XHJT/p/3897440.html"
"https://www.cnblogs.com/dolphin0520/p/3932921.html"
标签:rmi policy 处理器 mit locking clear 方法区 不同的 nal
原文地址:https://www.cnblogs.com/yjfb/p/12490595.html