Java study notes: multithreading1

I. Overview and significance of processes and threads

1, process
a, Overview: The process is that the program is running, the system resource allocation and called independent units. Each process has its own memory space and system resources.
b, meaning multi-process: a single process computer can only do one thing. And we are now the computer can while playing the game (game process), while listening to music (music course), so we have a common operating systems are multi-process operating system. That you can perform multiple tasks at a same time period. The role of multi-process not improve execution speed, but to improve CPU utilization.
2, thread
a, Overview: they can perform multiple tasks within a process, and that every task we can be seen as a thread. A thread is the basic unit of CPU utilization program.
b, multi-threaded meaning: multithreaded role is not to improve execution speed, but to increase application usage .
c, concurrent with the parallel
concurrent refers to a period of time while running a plurality of programs;
parallel refers to a point in time to run multiple programs at the same time;

Second, the multi-threaded implementation

Since the thread is dependent on the process exist, so we should first create out of a process. The process is created by the system, so we should go call the system functions to create a process. But Java is not calling the system function directly, so we have no way to directly implement multi-threaded programs. But Java can go to call C C ++ written procedures / to implement a multithreaded program. The C / C ++ to call the system functions to create a process, and then by the Java to call such a thing, and then provides classes for our use. We can achieve a multi-threaded program.
1, a multi-threaded implementation:
A: Tread statement subclass, the subclass overrides the run method of the thread class.
Ways to open thread: start method is called, can not repeat the open threads with a thread object
override the run method: run the code inside the method is to allow the thread to execute, so make the code thread of execution, you need to write to the inside run method

 class MyThread extends Thread{
            @Override
            public void run() {
                //一般run方法里面,放的是耗时的操作
                for (int i = 0; i < 100; i++) {
                    String name = this.getName();
                    System.out.println(name+"==="+i);
                }
            }
        }
    public class MyTest {
        public static void main(String[] args) {
            MyThread th1 = new MyThread();
            MyThread th2 = new MyThread();
            th1.start();
            th2.start();
        }
    }

B: get and set the thread object name

  • public final String getName () // get the thread name
  • public final void setName (String name) // Set the thread name

C: thread scheduling and getting and setting thread priorities

  • Thread of execution is random, which thread at some point grabbed the executive power of the cpu, cpu who executed

  • Thread scheduling, there are two models: There are time-sharing scheduling and preemptive scheduling model. java thread scheduling is preemptive model.

  • Time-sharing scheduling model: the right to use all the threads take turns using the cpu, the average allocation for each thread consumes cpu time slice

  • Preemptive model: giving priority to high-priority threads cpu, relatively more if the thread priority will be the same as that of a random selection of high-priority thread gets the cpu time

  • Set and get the thread priority:

  • public final int getPriority () // get priority thread

  • public final void setPriority (int newPriority) // Set the thread priority

Note: Sometimes we have to set up a thread specified priority, but the thread is not in accordance with the high priority thread execution, because of the size of the thread priority of this thread only represents the probability of being executed by the CPU increases but we all know that multi-threaded random, so sometimes run once or twice can not explain the problem.
2, multi-threaded implementation II:
Statement class that implements the Runnable interface, the class override the run () method, create a sub-class object interface, create a Thread object, interface subclass object as a parameter passed Thread, start threads.

class MyRunable implements Runnable{ 
    @Override
    public void run() {
        //需要线程执行代码
        for (int i = 0; i < 100; i++) {
            String name = Thread.currentThread().getName();
            System.out.println(name+"==="+i);
        }
    }
}
public class MyTest {
  public static void main(String[] args) {
        //Thread(Runnable target)
        //分配新的 Thread 对象。
        //Thread(Runnable target, String name) 参数2 线程名字
        MyRunable myRunable = new MyRunable();
        Thread th1 = new Thread(myRunable,"线程A");
        Thread th2 = new Thread(myRunable,"线程B");
        th1.start();
        th2.start();
   }
}

3, multi-threaded implementation Three:
Create a class that implements the Callable interface to create a subclass of the class FutureTask Callable interface as a parameter passed into the Thread class is created, the object as a parameter passed into FutureTask

public class MyCallable implements Callable<Integer> {
    //让线程来执行的方法
    @Override
    public Integer call() throws Exception {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName()+"==="+i);
        }
        return 100;
    }
}
    public class MyTest {
        public static void main(String[] args) throws Exception {
            MyCallable myCallable = new MyCallable();
            //FutureTask 这个是Runable接口的子类, 他可以封装一个Callable 任务
            FutureTask<Integer> task = new FutureTask<>(myCallable);
            Thread th1 = new Thread(task);
            th1.start();
            Integer integer = task.get();   //get()方法,可以获取线程执行完之后返回的结果
            System.out.println(integer);
        }
    }

Note: call () method and the run () are to thread to execute, the difference is executing the call to return the results and this method may throw an exception. run () thread execution is over, no results are returned, you can not throw an exception.
4, thread common method

  • public static Thread currentThread (); returns a reference to the currently executing thread object is.
  • public static void sleep (long millis) ; thread sleeps
  • Threads are: public final void join (); wait for the thread executing the following, other threads can begin, then add the following line Chengkai Qi.
  • public static void yield (); thread comity, pause the currently executing thread object, and turn on the other thread
  • public final void setDaemon (boolean on) ; set up a daemon thread, the main thread is a user thread when the user thread after death, also died immediately daemon thread
  • public final void stop (); forcibly stop the thread so that the thread is in a state of death
  • public void interrupt (); blocked interrupted thread

5, security thread
A, data security issues in line with the three conditions

  • a: is not multi-threaded
  • b: Are there multiple threads share data
  • c: if more than one statement in this operation data

B, to solve the problem of data security
a, problems with the program, because it meets the three criteria above, then we just will disrupt this standard, we can solve this problem. And the above criteria a, b is not disrupted, So we can only do processing c, the key is how to deal with? If we put multiple statements operation of shared data to see made into a whole, when one thread executes this whole time, other threads in a wait state, is to say when when a thread executes the whole, other threads can not be executed.
b, the basic idea: let the program no environmental security issues. The operation of the code multiple statements to share data locked up, so that at any time only one thread can execute. Requires synchronization code blocks:
C, Format:

synchronized(对象){//不能在括号里直接new 对象 new 了 就没效果
    			要被同步的代码 ;
    		}
注意:	这个同步代码块保证数据的安全性的一个主要因素就是这个对象
	    这个对象要定义为静态成员变量 才能被所有线程共享
    	这个对象其实就是一把锁.

Sync block locked object: Object to any one
synchronization method locked object: this is a
locked object static synchronization method: that corresponding to the current class bytecode file object

C, the benefits of synchronization: Synchronization occurs to solve the security problems of multithreading.
D, synchronization of drawbacks: when a thread is quite a long time, because each thread synchronization lock on to judge, this is a very resource-intensive, would effectively reduce the efficiency of the program.
Expand
in java programming, often need to use synchronous, and probably the most used is the synchronized keyword, because the synchronized keyword related to the concept of locks, so the first to understand some of the relevant knowledge lock.

  • java built-in locks: Each java object can be used as a synchronization locks, these locks to be built lock. When a thread enters a synchronized block or method of automatically acquire the lock, when you exit the synchronized block or method releases the lock. The only way to get the lock is built into this block or a sync lock protection method.
  • java is a built-in lock mutex, which is meant at most only one thread can acquire the lock, when the thread A thread B attempts to get hold of the built-in lock, thread A must wait or block until the thread releases the lock B If the thread does not release the lock B, then A thread will wait forever.
  • java objects and locks Locks: java classes and objects lock latch lock is substantially uniform and the built-in concept of the lock, however, is actually two locks are very different, the object is a lock object instance methods, or in the instance of an object class is the lock on the class object or a class of static methods for the class. We know that the class of object instances can be many, but each class has only one class object, the object lock a different object instances interfere with each other, but each class has only one class lock. But one thing must be noted that, in fact, like a lock just something conceptual, there is not real, it is only used to help us understand the difference between locking instance methods and static methods of.

For example:

 某电影院目前正在上映贺岁大片,共有100张票,而它有3个售票窗口售票,请设计一个程序模拟该电影院售票。
 分析:
 	a: 三个窗口其实就是3个线程
  	b: 定义票的数量100张
  	c: 创建线程对象,启动线程. 每卖一张这个票数应该--
class CellRunable implements Runnable{
   static int piao=100;
   static Object obj=new Object();
   @Override
   public void run() {
      while (true) {
      //只要任意一个线程,进入了同步代码块了以后,就会锁上(这个线程就会持有这把锁),其他线程,获取不到这个锁就处于阻塞状态
      //java 中这种内置的锁,我们称之为互斥锁
        synchronized (obj){ //同步代码块 锁对像 ,可以传任意一个对象 ,注意多个对象要共享一把锁
        //进来之后 说白了就是一个单线程环境
           if (piao > 0) {
              try {
                  Thread.sleep(50);
              } catch (InterruptedException e) {
                  e.printStackTrace();
               }
       System.out.println(Thread.currentThread().getName() + "正在出售 " + (piao--) + " 张票");
            }
       }
    //出来之后,才会释放锁
    }
  }
}
public class MyTest {
  public static void main(String[] args) {
    //synchronized 效率低  耗费性能
    CellRunable cellRunable = new CellRunable();
    Thread th1 = new Thread(cellRunable);
    Thread th2 = new Thread(cellRunable);
    Thread th3 = new Thread(cellRunable);
    th1.setName("窗口1");
    th2.setName("窗口2");
    th3.setName("窗口3");
    th1.start();
    th2.start();
    th3.start();
  }
}
Published 24 original articles · won praise 11 · views 2050

Guess you like

Origin blog.csdn.net/weixin_43791069/article/details/86603416