The inheritance thread method implements multithreading
public class Test extends Thread {
public void Run ()
{
System.out.println (This.getname ());
}
public static void Main (string[] args)
{
System.out.println (Thread.CurrentThread (). GetName ());
Test thread1 = new test ();
Test thread2 = new test ();
Thread1.start ();
Thread2.start ();
}
}
Implement Runnable interface method to realize multithreading
/*1. Instantiates the class that implements the Runnable interface.
2. Create a thread object and pass the first instance of the object as a parameter into the thread class's construction method. */
public class Test implements Runnable
{
public void Run ()
{
System.out.println (Thread.CurrentThread (). GetName ());
}
public static void Main (string[] args)
{
Test T1 = new test ();
Test t2 = new Test ();
MYTHREAD1 Thread Name
Thread thread1 = new Thread (T1, "MyThread1");
Thread thread2 = new Thread (t2);
Define thread name as MyThread2
Thread2.setname ("MyThread2");
Thread1.start ();
Thread2.start ();
}
}
4 threads, two threads to J plus 1, two threads to J minus 1
public class test{
private int J;
public static void Main (string[] args) {
Test T = new Test ();
Add add = t.new add ();
Sub Sub = T.new sub ();
for (int i=0;i<2;i++) {
thread T1 = new thread (add);
T1.start ();
Thread t2 = new Thread (sub);
T2.start ();
}
}
/* Here the Add method and sub method add the Synchronized keyword because when two threads manipulate the same variable at the same time,
* Even if the simple J + + operation, at the bottom of the system is also through a number of machine statements to implement, so in the implementation of the J + + process is also time-consuming,
* At this point it is possible that when J + + is executed, another thread H operates on J, so another thread H may operate
* is not the latest value. Therefore, you provide thread synchronization.
*/
Private synchronized void Add () {
j + +;
System.out.println ("1 ——————" +j);
}
Private synchronized void sub () {
j--;
System.out.println ("2 ——————" +j);
}
Add thread
public class ADD implements runnable{
public void Run () {
TODO auto-generated Method Stub
for (int i=0;i<1000;i++) {
Add ();
}
}
}
Reduce thread
public class SUB implements runnable{
public void Run () {
TODO auto-generated Method Stub
for (int i=0;i<1000;i++) {
Sub ();
}
}
}
}